{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "63cbc78f", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:16:58.768563Z", "iopub.status.busy": "2025-03-25T05:16:58.768381Z", "iopub.status.idle": "2025-03-25T05:16:58.963015Z", "shell.execute_reply": "2025-03-25T05:16:58.962592Z" } }, "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 = \"Gastroesophageal_reflux_disease_(GERD)\"\n", "cohort = \"GSE68698\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Gastroesophageal_reflux_disease_(GERD)\"\n", "in_cohort_dir = \"../../input/GEO/Gastroesophageal_reflux_disease_(GERD)/GSE68698\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Gastroesophageal_reflux_disease_(GERD)/GSE68698.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Gastroesophageal_reflux_disease_(GERD)/gene_data/GSE68698.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Gastroesophageal_reflux_disease_(GERD)/clinical_data/GSE68698.csv\"\n", "json_path = \"../../output/preprocess/Gastroesophageal_reflux_disease_(GERD)/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "cb7fcc99", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "5b084ca2", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:16:58.964533Z", "iopub.status.busy": "2025-03-25T05:16:58.964383Z", "iopub.status.idle": "2025-03-25T05:16:59.049446Z", "shell.execute_reply": "2025-03-25T05:16:59.049016Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Molecular characterization of systemic sclerosis esophageal pathology identifies inflammatory and proliferative signatures\"\n", "!Series_summary\t\"Esophageal involvement in patients with systemic sclerosis (SSc) is common, but tissue-specific pathological mechanisms are poorly understood. Fibrosis in the esophagus is thought to disrupt smooth muscle function and lead to esophageal dilatation, but autopsy studies demonstrate esophageal smooth muscle atrophy and the absence of fibrosis in the majority of SSc cases. Molecular characterization of SSc esophageal pathology is lacking. Herein, we perform a detailed characterization of SSc esophageal histopathology and molecular signatures at the level of gene expression. Esophageal biopsies were prospectively obtained during esophagogastroduodenoscopy in 16 consecutive SSc patients and 7 subjects without SSc. Upper and lower esophageal biopsies were evaluated for histopathology and gene expression. Individual patient’s upper and lower esophageal biopsies showed nearly identical patterns of gene expression. Similar to skin, inflammatory and proliferative gene expression signatures were identified suggesting that molecular subsets are a universal feature of SSc end-target organ pathology. The inflammatory signature was present in biopsies without high numbers of infiltrating lymphocytes. Molecular classification of esophageal biopsies was independent of SSc skin subtype, serum autoantibodies and esophagitis. Proliferative and inflammatory molecular gene expression subsets in tissues from patients with SSc may be a conserved, reproducible component of SSc pathogenesis. The inflammatory signature is observed in biopsies that lack large inflammatory infiltrates suggesting that immune activation is a major driver of SSc esophageal pathogenesis.\"\n", "!Series_overall_design\t\"Gene expression was measured in upper and lower esophageal biopsies from 16 patients with and 7 subjects without SSc.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['case/control: control', 'case/control: case'], 1: ['tissue: esophageal biopsy'], 2: ['biopsy site: lower', 'biopsy site: upper'], 3: ['batch: 1', 'batch: 2', 'batch: 3'], 4: ['systemic sclerosis subtype: NA', 'systemic sclerosis subtype: dcSSc', 'systemic sclerosis subtype: lcSSc'], 5: ['patient/control id: control 01', 'patient/control id: control 02', 'patient/control id: control 03', 'patient/control id: control 04', 'patient/control id: control 05', 'patient/control id: control 06', 'patient/control id: control 07', 'patient/control id: patient 01', 'patient/control id: patient 02', 'patient/control id: patient 03', 'patient/control id: patient 04', 'patient/control id: patient 05', 'patient/control id: patient 06', 'patient/control id: patient 08', 'patient/control id: patient 09', 'patient/control id: patient 11', 'patient/control id: patient 12', 'patient/control id: patient 13', 'patient/control id: patient 14', 'patient/control id: patient 15', 'patient/control id: patient 17', 'patient/control id: patient 18', 'patient/control id: patient 19']}\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": "1d079518", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "01516934", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:16:59.050789Z", "iopub.status.busy": "2025-03-25T05:16:59.050675Z", "iopub.status.idle": "2025-03-25T05:16:59.059643Z", "shell.execute_reply": "2025-03-25T05:16:59.059263Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Clinical Feature Preview:\n", "{'GSM1679252': [0.0], 'GSM1679253': [0.0], 'GSM1679254': [0.0], 'GSM1679255': [0.0], 'GSM1679256': [0.0], 'GSM1679257': [0.0], 'GSM1679258': [0.0], 'GSM1679259': [0.0], 'GSM1679260': [0.0], 'GSM1679261': [0.0], 'GSM1679262': [0.0], 'GSM1679263': [0.0], 'GSM1679264': [0.0], 'GSM1679265': [1.0], 'GSM1679266': [1.0], 'GSM1679267': [1.0], 'GSM1679268': [1.0], 'GSM1679269': [1.0], 'GSM1679270': [1.0], 'GSM1679271': [1.0], 'GSM1679272': [1.0], 'GSM1679273': [1.0], 'GSM1679274': [1.0], 'GSM1679275': [1.0], 'GSM1679276': [1.0], 'GSM1679277': [1.0], 'GSM1679278': [1.0], 'GSM1679279': [1.0], 'GSM1679280': [1.0], 'GSM1679281': [1.0], 'GSM1679282': [1.0], 'GSM1679283': [1.0], 'GSM1679284': [1.0], 'GSM1679285': [1.0], 'GSM1679286': [1.0], 'GSM1679287': [1.0], 'GSM1679288': [1.0], 'GSM1679289': [1.0], 'GSM1679290': [1.0], 'GSM1679291': [1.0], 'GSM1679292': [1.0], 'GSM1679293': [1.0], 'GSM1679294': [1.0], 'GSM1679295': [1.0], 'GSM1679296': [1.0], 'GSM1679297': [1.0]}\n", "Clinical data saved to ../../output/preprocess/Gastroesophageal_reflux_disease_(GERD)/clinical_data/GSE68698.csv\n" ] } ], "source": [ "# 1. Gene Expression Data Availability\n", "# Based on the background information, the dataset measures gene expression in esophageal biopsies\n", "# from patients with and without systemic sclerosis (SSc).\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "\n", "# For trait (Gastroesophageal reflux disease/GERD):\n", "# The sample characteristics indicate case/control data is available at index 0\n", "# The cases are patients with systemic sclerosis which can cause GERD\n", "trait_row = 0\n", "\n", "# For age:\n", "# Age information is not present in the sample characteristics dictionary\n", "age_row = None\n", "\n", "# For gender:\n", "# Gender information is not present in the sample characteristics dictionary\n", "gender_row = None\n", "\n", "# 2.2 Data Type Conversion\n", "\n", "def convert_trait(value):\n", " \"\"\"Convert trait value to binary format (0 for control, 1 for case).\"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract value after colon if present\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " if value.lower() == \"case\":\n", " return 1\n", " elif value.lower() == \"control\":\n", " return 0\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age value to continuous format.\"\"\"\n", " # Since age data is not available, this function won't be used,\n", " # but it's defined for completeness\n", " if value is None:\n", " return None\n", " \n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " try:\n", " return float(value)\n", " except (ValueError, TypeError):\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender value to binary format (0 for female, 1 for male).\"\"\"\n", " # Since gender data is not available, this function won't be used,\n", " # but it's defined for completeness\n", " if value is None:\n", " return None\n", " \n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip().lower()\n", " \n", " if value in [\"female\", \"f\"]:\n", " return 0\n", " elif value in [\"male\", \"m\"]:\n", " return 1\n", " else:\n", " return None\n", "\n", "# 3. Save Metadata - 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\n", "if trait_row is not None:\n", " # Extract clinical features using the geo_select_clinical_features function\n", " 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 if age_row is not None else None,\n", " gender_row=gender_row,\n", " convert_gender=convert_gender if gender_row is not None else None\n", " )\n", " \n", " # Preview the extracted clinical features\n", " preview = preview_df(clinical_df)\n", " print(\"Clinical Feature Preview:\")\n", " print(preview)\n", " \n", " # Create the directory for the clinical data if it doesn't exist\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " \n", " # Save the clinical data to a CSV file\n", " clinical_df.to_csv(out_clinical_data_file, index=False)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "3bb76bf1", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "2730b173", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:16:59.060679Z", "iopub.status.busy": "2025-03-25T05:16:59.060570Z", "iopub.status.idle": "2025-03-25T05:16:59.185735Z", "shell.execute_reply": "2025-03-25T05:16:59.185099Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Found data marker at line 89\n", "Header line: \"ID_REF\"\t\"GSM1679252\"\t\"GSM1679253\"\t\"GSM1679254\"\t\"GSM1679255\"\t\"GSM1679256\"\t\"GSM1679257\"\t\"GSM1679258\"\t\"GSM1679259\"\t\"GSM1679260\"\t\"GSM1679261\"\t\"GSM1679262\"\t\"GSM1679263\"\t\"GSM1679264\"\t\"GSM1679265\"\t\"GSM1679266\"\t\"GSM1679267\"\t\"GSM1679268\"\t\"GSM1679269\"\t\"GSM1679270\"\t\"GSM1679271\"\t\"GSM1679272\"\t\"GSM1679273\"\t\"GSM1679274\"\t\"GSM1679275\"\t\"GSM1679276\"\t\"GSM1679277\"\t\"GSM1679278\"\t\"GSM1679279\"\t\"GSM1679280\"\t\"GSM1679281\"\t\"GSM1679282\"\t\"GSM1679283\"\t\"GSM1679284\"\t\"GSM1679285\"\t\"GSM1679286\"\t\"GSM1679287\"\t\"GSM1679288\"\t\"GSM1679289\"\t\"GSM1679290\"\t\"GSM1679291\"\t\"GSM1679292\"\t\"GSM1679293\"\t\"GSM1679294\"\t\"GSM1679295\"\t\"GSM1679296\"\t\"GSM1679297\"\n", "First data line: \"A_23_P100001\"\t-1.834984\t-1.82578\t-0.599947\t-0.132206\t0.017572\t0.187431\t0.430457\t0.393148\t0.194504\t-0.673462\t-1.431611\t0.289414\t0.296018\t-0.334698\t0.240983\t-0.017572\t0.096226\t0.942176\t0.45519\t0.281983\t0.071123\t-0.748888\t-1.05681\t0.504558\t0.087858\t-0.834236\t-0.154798\t-0.123127\t-0.366139\t0.343739\t0.061401\t-0.70192\t-1.565067\t0.058271\t-0.81479\t-0.392128\t0.255073\t0.886424\t-0.022299\t-0.258725\t-0.529493\t0.18639\t0.235261\t0.096575\t-0.402694\t-0.208534\n", "Index(['A_23_P100001', 'A_23_P100056', 'A_23_P100074', 'A_23_P100092',\n", " 'A_23_P100103', 'A_23_P100111', 'A_23_P100127', 'A_23_P100133',\n", " 'A_23_P100141', 'A_23_P100156', 'A_23_P100196', 'A_23_P100203',\n", " 'A_23_P100220', 'A_23_P100240', 'A_23_P10025', 'A_23_P100263',\n", " 'A_23_P100292', 'A_23_P100315', 'A_23_P100326', 'A_23_P100341'],\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": "12ad4723", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "1bf91a27", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:16:59.187093Z", "iopub.status.busy": "2025-03-25T05:16:59.186959Z", "iopub.status.idle": "2025-03-25T05:16:59.189243Z", "shell.execute_reply": "2025-03-25T05:16:59.188809Z" } }, "outputs": [], "source": [ "# Based on the output, I can see that the gene identifiers start with \"A_23_P\" followed by numbers\n", "# These are Agilent microarray probe IDs, not standard human gene symbols\n", "# They need to be mapped to standard gene symbols for proper analysis\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "d73da8fb", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "8839828d", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:16:59.190613Z", "iopub.status.busy": "2025-03-25T05:16:59.190309Z", "iopub.status.idle": "2025-03-25T05:16:59.579352Z", "shell.execute_reply": "2025-03-25T05:16:59.578712Z" } }, "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 = GSE68698\n", "Line 6: !Series_title = Molecular characterization of systemic sclerosis esophageal pathology identifies inflammatory and proliferative signatures\n", "Line 7: !Series_geo_accession = GSE68698\n", "Line 8: !Series_status = Public on Oct 19 2015\n", "Line 9: !Series_submission_date = May 08 2015\n", "Line 10: !Series_last_update_date = Jan 23 2019\n", "Line 11: !Series_pubmed_id = 26220546\n", "Line 12: !Series_summary = Esophageal involvement in patients with systemic sclerosis (SSc) is common, but tissue-specific pathological mechanisms are poorly understood. Fibrosis in the esophagus is thought to disrupt smooth muscle function and lead to esophageal dilatation, but autopsy studies demonstrate esophageal smooth muscle atrophy and the absence of fibrosis in the majority of SSc cases. Molecular characterization of SSc esophageal pathology is lacking. Herein, we perform a detailed characterization of SSc esophageal histopathology and molecular signatures at the level of gene expression. Esophageal biopsies were prospectively obtained during esophagogastroduodenoscopy in 16 consecutive SSc patients and 7 subjects without SSc. Upper and lower esophageal biopsies were evaluated for histopathology and gene expression. Individual patient’s upper and lower esophageal biopsies showed nearly identical patterns of gene expression. Similar to skin, inflammatory and proliferative gene expression signatures were identified suggesting that molecular subsets are a universal feature of SSc end-target organ pathology. The inflammatory signature was present in biopsies without high numbers of infiltrating lymphocytes. Molecular classification of esophageal biopsies was independent of SSc skin subtype, serum autoantibodies and esophagitis. Proliferative and inflammatory molecular gene expression subsets in tissues from patients with SSc may be a conserved, reproducible component of SSc pathogenesis. The inflammatory signature is observed in biopsies that lack large inflammatory infiltrates suggesting that immune activation is a major driver of SSc esophageal pathogenesis.\n", "Line 13: !Series_overall_design = Gene expression was measured in upper and lower esophageal biopsies from 16 patients with and 7 subjects without SSc.\n", "Line 14: !Series_type = Expression profiling by array\n", "Line 15: !Series_contributor = Monique,,Hinchcliff\n", "Line 16: !Series_contributor = Guang,Y,Yang\n", "Line 17: !Series_contributor = Viktor,,Martyanov\n", "Line 18: !Series_contributor = Tammara,A,Wood\n", "Line 19: !Series_contributor = Barbara,,Jung\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene annotation preview:\n", "{'ID': ['A_23_P100001', 'A_23_P100011', 'A_23_P100022', 'A_23_P100056', 'A_23_P100074'], 'SPOT_ID': ['A_23_P100001', 'A_23_P100011', 'A_23_P100022', 'A_23_P100056', 'A_23_P100074'], 'CONTROL_TYPE': ['FALSE', 'FALSE', 'FALSE', 'FALSE', 'FALSE'], 'REFSEQ': ['NM_207446', 'NM_005829', 'NM_014848', 'NM_194272', 'NM_020371'], 'GB_ACC': ['NM_207446', 'NM_005829', 'NM_014848', 'NM_194272', 'NM_020371'], 'GENE': [400451.0, 10239.0, 9899.0, 348093.0, 57099.0], 'GENE_SYMBOL': ['FAM174B', 'AP3S2', 'SV2B', 'RBPMS2', 'AVEN'], 'GENE_NAME': ['family with sequence similarity 174, member B', 'adaptor-related protein complex 3, sigma 2 subunit', 'synaptic vesicle glycoprotein 2B', 'RNA binding protein with multiple splicing 2', 'apoptosis, caspase activation inhibitor'], 'UNIGENE_ID': ['Hs.27373', 'Hs.632161', 'Hs.21754', 'Hs.436518', 'Hs.555966'], 'ENSEMBL_ID': ['ENST00000557398', nan, 'ENST00000557410', 'ENST00000300069', 'ENST00000306730'], 'TIGR_ID': [nan, nan, nan, nan, nan], 'ACCESSION_STRING': ['ref|NM_207446|ens|ENST00000557398|ens|ENST00000553393|ens|ENST00000327355', 'ref|NM_005829|ref|NM_001199058|ref|NR_023361|ref|NR_037582', 'ref|NM_014848|ref|NM_001167580|ens|ENST00000557410|ens|ENST00000330276', 'ref|NM_194272|ens|ENST00000300069|gb|AK127873|gb|AK124123', 'ref|NM_020371|ens|ENST00000306730|gb|AF283508|gb|BC010488'], 'CHROMOSOMAL_LOCATION': ['chr15:93160848-93160789', 'chr15:90378743-90378684', 'chr15:91838329-91838388', 'chr15:65032375-65032316', 'chr15:34158739-34158680'], 'CYTOBAND': ['hs|15q26.1', 'hs|15q26.1', 'hs|15q26.1', 'hs|15q22.31', 'hs|15q14'], 'DESCRIPTION': ['Homo sapiens family with sequence similarity 174, member B (FAM174B), mRNA [NM_207446]', 'Homo sapiens adaptor-related protein complex 3, sigma 2 subunit (AP3S2), transcript variant 1, mRNA [NM_005829]', 'Homo sapiens synaptic vesicle glycoprotein 2B (SV2B), transcript variant 1, mRNA [NM_014848]', 'Homo sapiens RNA binding protein with multiple splicing 2 (RBPMS2), mRNA [NM_194272]', 'Homo sapiens apoptosis, caspase activation inhibitor (AVEN), mRNA [NM_020371]'], 'GO_ID': ['GO:0016020(membrane)|GO:0016021(integral to membrane)', 'GO:0005794(Golgi apparatus)|GO:0006886(intracellular protein transport)|GO:0008565(protein transporter activity)|GO:0016020(membrane)|GO:0016192(vesicle-mediated transport)|GO:0030117(membrane coat)|GO:0030659(cytoplasmic vesicle membrane)|GO:0031410(cytoplasmic vesicle)', 'GO:0001669(acrosomal vesicle)|GO:0006836(neurotransmitter transport)|GO:0016020(membrane)|GO:0016021(integral to membrane)|GO:0022857(transmembrane transporter activity)|GO:0030054(cell junction)|GO:0030672(synaptic vesicle membrane)|GO:0031410(cytoplasmic vesicle)|GO:0045202(synapse)', 'GO:0000166(nucleotide binding)|GO:0003676(nucleic acid binding)', 'GO:0005515(protein binding)|GO:0005622(intracellular)|GO:0005624(membrane fraction)|GO:0006915(apoptosis)|GO:0006916(anti-apoptosis)|GO:0012505(endomembrane system)|GO:0016020(membrane)'], 'SEQUENCE': ['ATCTCATGGAAAAGCTGGATTCCTCTGCCTTACGCAGAAACACCCGGGCTCCATCTGCCA', 'TCAAGTATTGGCCTGACATAGAGTCCTTAAGACAAGCAAAGACAAGCAAGGCAAGCACGT', 'ATGTCGGCTGTGGAGGGTTAAAGGGATGAGGCTTTCCTTTGTTTAGCAAATCTGTTCACA', 'CCCTGTCAGATAAGTTTAATGTTTAGTTTGAGGCATGAAGAAGAAAAGGGTTTCCATTCT', 'GACCAGCCAGTTTACAAGCATGTCTCAAGCTAGTGTGTTCCATTATGCTCACAGCAGTAA']}\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": "be4e3ff0", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "ffa48b6c", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:16:59.580839Z", "iopub.status.busy": "2025-03-25T05:16:59.580717Z", "iopub.status.idle": "2025-03-25T05:17:02.215519Z", "shell.execute_reply": "2025-03-25T05:17:02.214842Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Number of mappings found: 30936\n", "First few probe-to-gene mappings:\n", " ID Gene\n", "0 A_23_P100001 FAM174B\n", "1 A_23_P100011 AP3S2\n", "2 A_23_P100022 SV2B\n", "3 A_23_P100056 RBPMS2\n", "4 A_23_P100074 AVEN\n", "Number of unique genes after mapping: 13572\n", "First few gene symbols:\n", "Index(['A1BG', 'A1BG-AS1', 'A1CF', 'A2LD1', 'A2M', 'A2ML1', 'A4GALT', 'AAAS',\n", " 'AACS', 'AADAC', 'AADAT', 'AAGAB', 'AAMP', 'AANAT', 'AARS', 'AARS2',\n", " 'AARSD1', 'AASDH', 'AASDHPPT', 'AASS'],\n", " dtype='object', name='Gene')\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data saved to ../../output/preprocess/Gastroesophageal_reflux_disease_(GERD)/gene_data/GSE68698.csv\n" ] } ], "source": [ "# 1. Identify the ID and gene symbol columns from gene annotation data\n", "# Based on the gene annotation preview, 'ID' contains the probe identifiers (e.g., A_23_P100001)\n", "# and 'GENE_SYMBOL' contains the corresponding gene symbols (e.g., FAM174B)\n", "id_column = 'ID' # This matches the index in gene_data\n", "gene_symbol_column = 'GENE_SYMBOL'\n", "\n", "# 2. Get gene mapping dataframe\n", "# First, extract the full gene annotation data from the SOFT file\n", "gene_annotation = get_gene_annotation(soft_file)\n", "\n", "# Create the mapping between probe IDs and gene symbols\n", "mapping_df = get_gene_mapping(gene_annotation, id_column, gene_symbol_column)\n", "print(f\"Number of mappings found: {len(mapping_df)}\")\n", "print(\"First few probe-to-gene mappings:\")\n", "print(mapping_df.head())\n", "\n", "# 3. Apply gene mapping to convert probe-level measurements to gene expression data\n", "gene_data = apply_gene_mapping(gene_data, mapping_df)\n", "print(f\"Number of unique genes after mapping: {len(gene_data)}\")\n", "print(\"First few gene symbols:\")\n", "print(gene_data.index[:20])\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" ] }, { "cell_type": "markdown", "id": "4770401e", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "4879cdd3", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:17:02.217138Z", "iopub.status.busy": "2025-03-25T05:17:02.216855Z", "iopub.status.idle": "2025-03-25T05:17:07.858809Z", "shell.execute_reply": "2025-03-25T05:17:07.858164Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Loaded gene data shape: (13572, 46)\n", "Gene data shape after normalization: (13483, 46)\n", "Sample gene symbols after normalization: ['A1BG', 'A1BG-AS1', 'A1CF', 'A2M', 'A2ML1', 'A4GALT', 'AAAS', 'AACS', 'AADAC', 'AADAT']\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data saved to ../../output/preprocess/Gastroesophageal_reflux_disease_(GERD)/gene_data/GSE68698.csv\n", "Loaded clinical data shape: (1, 46)\n", "Linked data shape: (46, 13484)\n", "Linked data preview (first 5 rows, first 5 columns):\n", " Gastroesophageal_reflux_disease_(GERD) A1BG A1BG-AS1 \\\n", "GSM1679252 0.0 -0.467114 -0.046106 \n", "GSM1679253 0.0 -0.085174 0.038475 \n", "GSM1679254 0.0 -0.002690 0.208568 \n", "GSM1679255 0.0 0.034070 0.120268 \n", "GSM1679256 0.0 0.394492 0.099820 \n", "\n", " A1CF A2M \n", "GSM1679252 -1.033794 0.015503 \n", "GSM1679253 -0.862933 0.224771 \n", "GSM1679254 0.017483 -0.690636 \n", "GSM1679255 1.001625 -0.925642 \n", "GSM1679256 0.389577 -0.378413 \n", "\n", "Missing values before handling:\n", " Trait (Gastroesophageal_reflux_disease_(GERD)) missing: 0 out of 46\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: (46, 13484)\n", "For the feature 'Gastroesophageal_reflux_disease_(GERD)', the least common label is '0.0' with 13 occurrences. This represents 28.26% of the dataset.\n", "The distribution of the feature 'Gastroesophageal_reflux_disease_(GERD)' in this dataset is fine.\n", "\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data saved to ../../output/preprocess/Gastroesophageal_reflux_disease_(GERD)/GSE68698.csv\n" ] } ], "source": [ "# 1. Load the gene expression data saved in step 6\n", "gene_data = pd.read_csv(out_gene_data_file, index_col=0)\n", "print(f\"Loaded gene data shape: {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", "print(f\"Sample gene symbols after normalization: {list(normalized_gene_data.index[:10])}\")\n", "\n", "# Save the normalized gene data (overwrite the previous file with normalized 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. Load the clinical data created in step 2\n", "clinical_df = pd.read_csv(out_clinical_data_file)\n", "print(f\"Loaded clinical data shape: {clinical_df.shape}\")\n", "\n", "# If clinical_df doesn't have a proper index, fix it\n", "if 'Unnamed: 0' in clinical_df.columns:\n", " clinical_df = clinical_df.set_index('Unnamed: 0')\n", "elif not clinical_df.index.name:\n", " # Just in case the index needs to be set from data\n", " clinical_features = 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 if age_row is not None else None,\n", " gender_row=gender_row,\n", " convert_gender=convert_gender if gender_row is not None else None\n", " )\n", " clinical_df = clinical_features\n", "\n", "# Link clinical and genetic data\n", "linked_data = geo_link_clinical_genetic_data(clinical_df, normalized_gene_data)\n", "print(f\"Linked data shape: {linked_data.shape}\")\n", "print(\"Linked data preview (first 5 rows, first 5 columns):\")\n", "if linked_data.shape[1] >= 5:\n", " print(linked_data.iloc[:5, :5])\n", "else:\n", " print(linked_data.head())\n", "\n", "# 3. 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", "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", "if gene_cols:\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", "# 4. 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", "# 5. 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=len(normalized_gene_data) > 0, \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", "# 6. Save if usable\n", "if is_usable and len(cleaned_data) > 0:\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " cleaned_data.to_csv(out_data_file)\n", " print(f\"Linked data saved to {out_data_file}\")\n", "else:\n", " print(\"Data was determined to be unusable or empty and was not saved\")" ] } ], "metadata": { "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.16" } }, "nbformat": 4, "nbformat_minor": 5 }