{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "8291f1e4", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:12:35.996674Z", "iopub.status.busy": "2025-03-25T07:12:35.996571Z", "iopub.status.idle": "2025-03-25T07:12:36.153566Z", "shell.execute_reply": "2025-03-25T07:12:36.153251Z" } }, "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 = \"Irritable_bowel_syndrome_(IBS)\"\n", "cohort = \"GSE25220\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Irritable_bowel_syndrome_(IBS)\"\n", "in_cohort_dir = \"../../input/GEO/Irritable_bowel_syndrome_(IBS)/GSE25220\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Irritable_bowel_syndrome_(IBS)/GSE25220.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Irritable_bowel_syndrome_(IBS)/gene_data/GSE25220.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Irritable_bowel_syndrome_(IBS)/clinical_data/GSE25220.csv\"\n", "json_path = \"../../output/preprocess/Irritable_bowel_syndrome_(IBS)/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "ebeb0de8", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "2b92b8a8", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:12:36.154954Z", "iopub.status.busy": "2025-03-25T07:12:36.154821Z", "iopub.status.idle": "2025-03-25T07:12:36.247967Z", "shell.execute_reply": "2025-03-25T07:12:36.247688Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Transcription levels in human colon biopsies in IBS and IBD patients before and after participating in a high red-meat dietary intervention\"\n", "!Series_summary\t\"Study 1: Transcriptomic profiles in colon tissue from inflammatory bowel diseases patients in relation to N-nitroso compound exposure and colorectal cancer risk\"\n", "!Series_summary\t\"\"\n", "!Series_summary\t\"Study 1: N-nitroso compounds (NOC) have been suggested to play a role in human cancer development but definitive evidence is still lacking. In this study we investigated gene expression modifications induced in human colon tissue in relation to NOC exposure to gain insight in the relevance of these compounds in human colorectal cancer (CRC) development. Since there are indications that inflammation stimulates endogenous NOC formation, the study population consisted of patients with inflammatory bowel disease (IBD) and irritable bowel syndrome patients as controls without inflammation. Strong transcriptomic differences were identified in colonic biopsies from IBD patients and compared to controls that enhance the understanding of IBD pathophysiology. However, fecal NOC levels were not increased in IBD patients, suggesting that inflammation did not stimulate NOC formation. By relating gene expression changes of all subjects to fecal NOC levels, we did, however, identify a NOC exposure-associated transcriptomic response that suggests that physiological NOC concentrations may induce genotoxic responses and chromatin modifications in human colon tissue, both of which are linked to carcinogenicity. In a network analysis, chromatin modifications were linked to 11 significantly modulated histone genes, pointing towards a possible epigenetic mechanism that may be relevant in comprehending the molecular basis of NOC-induced carcinogenesis. We conclude that NOC exposure is associated with gene expression modifications in the colon that may increase CRC risk in humans.\"\n", "!Series_summary\t\"\"\n", "!Series_summary\t\"Study 2: Red meat intake-induced increases in fecal water genotoxicity correlate with pro-carcinogenic gene expression changes in the human colon\"\n", "!Series_summary\t\"\"\n", "!Series_summary\t\"Study 2: Red meat consumption is associated with an increased colorectal cancer (CRC) risk, which may be due to an increased endogenous formation of genotoxic N-nitroso compounds (NOCs). To assess the impact of red meat intake on potential risk factors of CRC, we investigated the effect of a 7-day dietary red meat intervention in human subjects on endogenous NOC formation and fecal water genotoxicity in relation to transcriptomic changes induced in colonic tissue. In order to evaluate the potential effect of an inflamed colon on endogenous nitrosation, the study population consisted of inflammatory bowel disease (IBD) and irritable bowel syndrome (IBS) control subjects without inflammation. The intervention had no effect on fecal NOC formation but fecal water genotoxicity significantly increased in response to red meat intake. Since IBD patients showed no difference in fecal NOC formation or fecal water genotoxicity levels as compared to IBS controls, for transcriptomic analyses, all subjects were grouped together. Genes significantly correlating with the increase in fecal water genotoxicity were involved in biological pathways indicative of genotoxic effects, including modifications in DNA damage, cell cycle, and apoptosis pathways. Moreover, WNT signaling and nucleosome remodeling pathways were modulated that are known to play a part in the carcinogenic process in the human colon. These results are in line with a possible oxidative effect of dietary heme. We conclude that the gene expression changes identified in this study corroborate the genotoxic potential of diets high in red meat and point towards a possible risk of CRC development in humans.\"\n", "!Series_overall_design\t\"The study investigated transcription levels in human colon biopsies obtained during a colonoscopic exam in 32 subjects suffering from either inflammatory bowel disease (IBD) or irritable bowel syndrome (IBS). IBS patients served as control patients for comparison with IBD patients (see Study 1). 12 of these patients (6 IBD and 6 IBS) also followed a 7-day diet high in red meat (300 grams/day) after which a second colonscopic exam was performed to obtain colon biopsies to investigate the effect of the red meat intervention (Study 2). For each subject, cRNA copies of mRNA isolated from the colon biopsies were labeled with one dye (Cy3) and each sample was hybridized on a separate array. One replicate per subject or before/after red meat intervention (so 44 arrays in total, i.e. 20 before patients and 12 before and after patients).\"\n", "Sample Characteristics Dictionary:\n", "{0: ['subject number: Subject2', 'subject number: Subject3', 'subject number: Subject4', 'subject number: Subject5', 'subject number: Subject6', 'subject number: Subject7', 'subject number: Subject8', 'subject number: Subject9', 'subject number: Subject10', 'subject number: Subject11', 'subject number: Subject12', 'subject number: Subject14', 'subject number: Subject15', 'subject number: Subject16', 'subject number: Subject17', 'subject number: Subject18', 'subject number: Subject19', 'subject number: Subject20', 'subject number: Subject21', 'subject number: Subject22', 'subject number: Subject23', 'subject number: Subject24', 'subject number: Subject25', 'subject number: Subject26', 'subject number: Subject27', 'subject number: Subject28', 'subject number: Subject29', 'subject number: Subject30', 'subject number: Subject31', 'subject number: Subject32'], 1: ['disease status: IBD', 'disease status: IBS'], 2: ['gender: male', 'gender: female'], 3: ['age: 57', 'age: 65', 'age: 44', 'age: 72', 'age: 60', 'age: 25', 'age: 31', 'age: 48', 'age: 54', 'age: 71', 'age: 63', 'age: 29', 'age: 61', 'age: 39', 'age: 55', 'age: 69', 'age: 53', 'age: 40', 'age: 51', 'age: 64', 'age: 47', 'age: 58', 'age: 46'], 4: ['intervention status: before', 'intervention status: after']}\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": "2958d275", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "c820578d", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:12:36.248960Z", "iopub.status.busy": "2025-03-25T07:12:36.248856Z", "iopub.status.idle": "2025-03-25T07:12:36.259255Z", "shell.execute_reply": "2025-03-25T07:12:36.258976Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Clinical Data Preview:\n", "{'GSM620750': [0.0, 57.0, 1.0], 'GSM620751': [0.0, 57.0, 1.0], 'GSM620752': [1.0, 65.0, 0.0], 'GSM620753': [1.0, 65.0, 0.0], 'GSM620754': [1.0, 44.0, 1.0], 'GSM620755': [0.0, 72.0, 1.0], 'GSM620756': [0.0, 60.0, 1.0], 'GSM620757': [0.0, 60.0, 1.0], 'GSM620758': [1.0, 57.0, 1.0], 'GSM620759': [1.0, 57.0, 1.0], 'GSM620760': [1.0, 25.0, 0.0], 'GSM620761': [1.0, 25.0, 0.0], 'GSM620762': [0.0, 31.0, 1.0], 'GSM620763': [0.0, 31.0, 1.0], 'GSM620764': [0.0, 48.0, 0.0], 'GSM620765': [0.0, 48.0, 0.0], 'GSM620766': [0.0, 54.0, 1.0], 'GSM620767': [0.0, 71.0, 1.0], 'GSM620768': [0.0, 71.0, 1.0], 'GSM620769': [1.0, 63.0, 0.0], 'GSM620770': [0.0, 29.0, 1.0], 'GSM620771': [0.0, 29.0, 1.0], 'GSM620772': [1.0, 61.0, 1.0], 'GSM620773': [1.0, 61.0, 1.0], 'GSM620774': [1.0, 39.0, 0.0], 'GSM620775': [1.0, 65.0, 1.0], 'GSM620776': [0.0, 55.0, 0.0], 'GSM620777': [1.0, 69.0, 1.0], 'GSM620778': [1.0, 65.0, 0.0], 'GSM620779': [0.0, 53.0, 1.0], 'GSM620780': [0.0, 40.0, 0.0], 'GSM620781': [0.0, 51.0, 1.0], 'GSM620782': [0.0, 54.0, 0.0], 'GSM620783': [0.0, 40.0, 1.0], 'GSM620784': [0.0, 40.0, 1.0], 'GSM620785': [1.0, 64.0, 1.0], 'GSM620786': [1.0, 64.0, 1.0], 'GSM620787': [0.0, 47.0, 1.0], 'GSM620788': [0.0, 54.0, 1.0], 'GSM620789': [1.0, 58.0, 0.0], 'GSM620790': [1.0, 58.0, 0.0], 'GSM620791': [1.0, 46.0, 1.0], 'GSM620792': [0.0, 46.0, 1.0], 'GSM620793': [0.0, 55.0, 1.0]}\n", "Clinical data saved to ../../output/preprocess/Irritable_bowel_syndrome_(IBS)/clinical_data/GSE25220.csv\n" ] } ], "source": [ "# 1. Gene Expression Data Availability\n", "# Based on the background information, this dataset contains transcriptomic data (gene expression)\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "\n", "# For trait: Disease status is available at index 1 (IBD vs IBS)\n", "trait_row = 1\n", "\n", "# For age: Age is available at index 3\n", "age_row = 3\n", "\n", "# For gender: Gender is available at index 2\n", "gender_row = 2\n", "\n", "# 2.2 Data Type Conversion\n", "def convert_trait(value):\n", " \"\"\"\n", " Convert trait value to binary (0 for IBS, 1 for IBD)\n", " Since we're studying IBS, the coding should be:\n", " - IBS (control/our trait of interest) = 1\n", " - IBD (different condition) = 0\n", " \"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract value after colon\n", " if \":\" in value:\n", " value = value.split(\":\")[1].strip()\n", " \n", " if value.upper() == \"IBS\":\n", " return 1 # Our trait of interest\n", " elif value.upper() == \"IBD\":\n", " return 0 # Not our trait of interest\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age value to continuous numeric value\"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract value after colon\n", " if \":\" in value:\n", " value = value.split(\":\")[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 (0 for female, 1 for male)\"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract value after colon\n", " if \":\" in value:\n", " value = value.split(\":\")[1].strip()\n", " \n", " if value.lower() == \"female\":\n", " return 0\n", " elif value.lower() == \"male\":\n", " return 1\n", " else:\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Determine if trait data is available\n", "is_trait_available = trait_row is not None\n", "\n", "# Conduct initial filtering\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\n", " clinical_selected = 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 data\n", " preview = preview_df(clinical_selected)\n", " print(\"Clinical Data Preview:\")\n", " print(preview)\n", " \n", " # Save to CSV\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " clinical_selected.to_csv(out_clinical_data_file, index=False)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "a3af81b2", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "6e78b020", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:12:36.260277Z", "iopub.status.busy": "2025-03-25T07:12:36.260176Z", "iopub.status.idle": "2025-03-25T07:12:36.392813Z", "shell.execute_reply": "2025-03-25T07:12:36.392439Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Found data marker at line 83\n", "Header line: \"ID_REF\"\t\"GSM620750\"\t\"GSM620751\"\t\"GSM620752\"\t\"GSM620753\"\t\"GSM620754\"\t\"GSM620755\"\t\"GSM620756\"\t\"GSM620757\"\t\"GSM620758\"\t\"GSM620759\"\t\"GSM620760\"\t\"GSM620761\"\t\"GSM620762\"\t\"GSM620763\"\t\"GSM620764\"\t\"GSM620765\"\t\"GSM620766\"\t\"GSM620767\"\t\"GSM620768\"\t\"GSM620769\"\t\"GSM620770\"\t\"GSM620771\"\t\"GSM620772\"\t\"GSM620773\"\t\"GSM620774\"\t\"GSM620775\"\t\"GSM620776\"\t\"GSM620777\"\t\"GSM620778\"\t\"GSM620779\"\t\"GSM620780\"\t\"GSM620781\"\t\"GSM620782\"\t\"GSM620783\"\t\"GSM620784\"\t\"GSM620785\"\t\"GSM620786\"\t\"GSM620787\"\t\"GSM620788\"\t\"GSM620789\"\t\"GSM620790\"\t\"GSM620791\"\t\"GSM620792\"\t\"GSM620793\"\n", "First data line: \"(+)E1A_r60_1\"\n", "Index(['(+)E1A_r60_1', '(+)E1A_r60_3', '(+)E1A_r60_a104', '(+)E1A_r60_a107',\n", " '(+)E1A_r60_a135', '(+)E1A_r60_a20', '(+)E1A_r60_a22', '(+)E1A_r60_a97',\n", " '(+)E1A_r60_n11', '(+)E1A_r60_n9', '(+)eQC-39', '(+)eQC-40',\n", " '(+)eQC-41', '(+)eQC-42', '(-)3xSLv1', 'A_23_P100001', 'A_23_P100011',\n", " 'A_23_P100022', 'A_23_P100056', 'A_23_P100074'],\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": "aab0bc59", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "b9d4b0cb", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:12:36.394150Z", "iopub.status.busy": "2025-03-25T07:12:36.394026Z", "iopub.status.idle": "2025-03-25T07:12:36.395954Z", "shell.execute_reply": "2025-03-25T07:12:36.395679Z" } }, "outputs": [], "source": [ "# Analyzing the gene identifiers\n", "# Example identifiers: '(+)E1A_r60_1', '(+)E1A_r60_3', 'A_23_P100001', 'A_23_P100011', etc.\n", "# These appear to be Agilent microarray probe identifiers, not standard human gene symbols\n", "# Agilent platform IDs like 'A_23_P100001' need to be mapped to human gene symbols\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "029ea68e", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "2c5d95ad", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:12:36.397096Z", "iopub.status.busy": "2025-03-25T07:12:36.396990Z", "iopub.status.idle": "2025-03-25T07:12:39.051455Z", "shell.execute_reply": "2025-03-25T07:12:39.051112Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "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. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n", "gene_annotation = get_gene_annotation(soft_file)\n", "\n", "# 2. Use the 'preview_df' function from the library to preview the data and print out the results.\n", "print(\"Gene annotation preview:\")\n", "print(preview_df(gene_annotation))\n" ] }, { "cell_type": "markdown", "id": "2f8f75a5", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "d1e0c746", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:12:39.052800Z", "iopub.status.busy": "2025-03-25T07:12:39.052679Z", "iopub.status.idle": "2025-03-25T07:12:39.581394Z", "shell.execute_reply": "2025-03-25T07:12:39.581016Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene mapping preview:\n", "{'ID': ['A_23_P100001', 'A_23_P100011', 'A_23_P100022', 'A_23_P100056', 'A_23_P100074'], 'Gene': ['FAM174B', 'AP3S2', 'SV2B', 'RBPMS2', 'AVEN']}\n", "\n", "Gene expression data preview:\n", "Number of genes: 18488\n", "Number of samples: 44\n", "First 5 genes:\n", "Index(['A1BG', 'A1BG-AS1', 'A1CF', 'A2LD1', 'A2M'], dtype='object', name='Gene')\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data saved to ../../output/preprocess/Irritable_bowel_syndrome_(IBS)/gene_data/GSE25220.csv\n" ] } ], "source": [ "# 1. Identify the columns that store gene identifiers and gene symbols\n", "# Based on the preview, we need to map from 'ID' to 'GENE_SYMBOL'\n", "probe_col = \"ID\" # Column that contains the probe identifiers from gene expression data\n", "gene_symbol_col = \"GENE_SYMBOL\" # Column that contains the gene symbols\n", "\n", "# 2. Create the gene mapping dataframe using the function from the library\n", "mapping_df = get_gene_mapping(gene_annotation, probe_col, gene_symbol_col)\n", "\n", "# Display the first few rows of the mapping dataframe to confirm\n", "print(\"Gene mapping preview:\")\n", "print(preview_df(mapping_df))\n", "\n", "# 3. Apply the gene mapping to convert from probe-level to gene-level expression\n", "gene_data = apply_gene_mapping(gene_data, mapping_df)\n", "\n", "# Display preview of the gene expression data\n", "print(\"\\nGene expression data preview:\")\n", "print(f\"Number of genes: {len(gene_data)}\")\n", "print(f\"Number of samples: {len(gene_data.columns)}\")\n", "print(\"First 5 genes:\")\n", "print(gene_data.index[:5])\n", "\n", "# Save the gene expression data to CSV file\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": "1e3cd99c", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "7e378b69", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:12:39.582857Z", "iopub.status.busy": "2025-03-25T07:12:39.582738Z", "iopub.status.idle": "2025-03-25T07:12:47.644515Z", "shell.execute_reply": "2025-03-25T07:12:47.644137Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "After normalization: 18247 genes remain\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene expression data saved to ../../output/preprocess/Irritable_bowel_syndrome_(IBS)/gene_data/GSE25220.csv\n", "Clinical data columns: ['GSM620750', 'GSM620751', 'GSM620752', 'GSM620753', 'GSM620754', 'GSM620755', 'GSM620756', 'GSM620757', 'GSM620758', 'GSM620759', 'GSM620760', 'GSM620761', 'GSM620762', 'GSM620763', 'GSM620764', 'GSM620765', 'GSM620766', 'GSM620767', 'GSM620768', 'GSM620769', 'GSM620770', 'GSM620771', 'GSM620772', 'GSM620773', 'GSM620774', 'GSM620775', 'GSM620776', 'GSM620777', 'GSM620778', 'GSM620779', 'GSM620780', 'GSM620781', 'GSM620782', 'GSM620783', 'GSM620784', 'GSM620785', 'GSM620786', 'GSM620787', 'GSM620788', 'GSM620789', 'GSM620790', 'GSM620791', 'GSM620792', 'GSM620793']\n", "Clinical data shape: (3, 44)\n", "Clinical data sample: GSM620750 GSM620751 GSM620752 GSM620753 GSM620754 GSM620755 \\\n", "0 0.0 0.0 1.0 1.0 1.0 0.0 \n", "1 57.0 57.0 65.0 65.0 44.0 72.0 \n", "2 1.0 1.0 0.0 0.0 1.0 1.0 \n", "\n", " GSM620756 GSM620757 GSM620758 GSM620759 ... GSM620784 GSM620785 \\\n", "0 0.0 0.0 1.0 1.0 ... 0.0 1.0 \n", "1 60.0 60.0 57.0 57.0 ... 40.0 64.0 \n", "2 1.0 1.0 1.0 1.0 ... 1.0 1.0 \n", "\n", " GSM620786 GSM620787 GSM620788 GSM620789 GSM620790 GSM620791 \\\n", "0 1.0 0.0 0.0 1.0 1.0 1.0 \n", "1 64.0 47.0 54.0 58.0 58.0 46.0 \n", "2 1.0 1.0 1.0 0.0 0.0 1.0 \n", "\n", " GSM620792 GSM620793 \n", "0 0.0 0.0 \n", "1 46.0 55.0 \n", "2 1.0 1.0 \n", "\n", "[3 rows x 44 columns]\n", "Trait column 'Irritable_bowel_syndrome_(IBS)' not found in clinical data. Loading raw clinical data...\n", "Recreated clinical data with correct trait column\n", "Found 44 common samples between clinical and genetic data\n", "Linked data shape: (44, 18248)\n", "Linked data columns preview: ['Irritable_bowel_syndrome_(IBS)', 'A1BG', 'A1BG-AS1', 'A1CF', 'A2M']\n", "Final linked data columns (first 10): ['Irritable_bowel_syndrome_(IBS)', 'A1BG', 'A1BG-AS1', 'A1CF', 'A2M', 'A2ML1', 'A4GALT', 'A4GNT', 'AAAS', 'AACS']\n", "Trait column exists: True\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Data after handling missing values: (44, 18248)\n", "For the feature 'Irritable_bowel_syndrome_(IBS)', the least common label is '1.0' with 19 occurrences. This represents 43.18% of the dataset.\n", "The distribution of the feature 'Irritable_bowel_syndrome_(IBS)' in this dataset is fine.\n", "\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data saved to ../../output/preprocess/Irritable_bowel_syndrome_(IBS)/GSE25220.csv\n" ] } ], "source": [ "# 1. Normalize gene symbols in the gene expression data\n", "# First load the gene expression data\n", "gene_data = pd.read_csv(out_gene_data_file, index_col=0)\n", "\n", "# Normalize gene symbols using the NCBI Gene database\n", "gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"After normalization: {len(gene_data)} genes remain\")\n", "\n", "# Save the normalized gene data\n", "gene_data.to_csv(out_gene_data_file)\n", "print(f\"Normalized gene expression data saved to {out_gene_data_file}\")\n", "\n", "# 2. Load the clinical data\n", "clinical_data = pd.read_csv(out_clinical_data_file)\n", "\n", "# Ensure proper column naming for clinical data\n", "if clinical_data.columns[0] == \"Unnamed: 0\":\n", " clinical_data = pd.read_csv(out_clinical_data_file, index_col=0)\n", "\n", "# Inspect what's in the clinical data\n", "print(\"Clinical data columns:\", clinical_data.columns.tolist())\n", "print(\"Clinical data shape:\", clinical_data.shape)\n", "print(\"Clinical data sample:\", clinical_data.head())\n", "\n", "# 3. Link the clinical and genetic data\n", "# Transpose gene data to have samples as rows and genes as columns\n", "gene_data_t = gene_data.T\n", "\n", "# Make sure the trait column exists in clinical data\n", "# If not, we need to load and process it again\n", "if trait not in clinical_data.columns:\n", " print(f\"Trait column '{trait}' not found in clinical data. Loading raw clinical data...\")\n", " \n", " # Load raw data again\n", " soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", " background_info, raw_clinical_data = get_background_and_clinical_data(matrix_file)\n", " \n", " # Process disease state row manually to ensure correct trait column\n", " disease_row = raw_clinical_data.iloc[trait_row]\n", " samples = [col for col in disease_row.index if col != \"!Sample_geo_accession\"]\n", " \n", " # Create a DataFrame for the trait values\n", " trait_data = pd.DataFrame(index=samples)\n", " \n", " # Process each sample's disease status\n", " for sample in samples:\n", " value = disease_row[sample]\n", " if pd.isna(value):\n", " trait_data.loc[sample, trait] = None\n", " else:\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " if \"IBS\" in value:\n", " trait_data.loc[sample, trait] = 1 # IBS is our target trait\n", " elif \"IBD\" in value:\n", " trait_data.loc[sample, trait] = 0 # IBD is the control\n", " else:\n", " trait_data.loc[sample, trait] = None\n", " \n", " clinical_data = trait_data\n", " print(\"Recreated clinical data with correct trait column\")\n", "\n", "# Find common samples between clinical and gene data\n", "common_samples = list(set(clinical_data.index) & set(gene_data_t.index))\n", "print(f\"Found {len(common_samples)} common samples between clinical and genetic data\")\n", "\n", "if len(common_samples) > 0:\n", " # Filter both datasets to include only common samples\n", " gene_data_filtered = gene_data_t.loc[common_samples]\n", " clinical_data_filtered = clinical_data.loc[common_samples]\n", " \n", " # Join the data\n", " linked_data = pd.concat([clinical_data_filtered, gene_data_filtered], axis=1)\n", " print(f\"Linked data shape: {linked_data.shape}\")\n", " print(f\"Linked data columns preview: {linked_data.columns[:5].tolist()}\")\n", "else:\n", " print(\"No common samples found. Unable to link data.\")\n", " # We can't proceed without linked data\n", " is_usable = False\n", " # Log this in the 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=True, \n", " is_biased=True, # Set to True as we can't use this data\n", " df=pd.DataFrame(), # Empty DataFrame\n", " note=\"Unable to link clinical and genetic data due to no common sample IDs.\"\n", " )\n", " # Exit early\n", " raise ValueError(\"No common samples found between clinical and gene data. Cannot proceed.\")\n", "\n", "# Verify trait column exists in linked data\n", "if trait not in linked_data.columns:\n", " print(f\"ERROR: Trait column '{trait}' still not found in linked data\")\n", " # Create a simple mapping if trait column missing\n", " linked_data[trait] = clinical_data_filtered[trait]\n", "\n", "print(f\"Final linked data columns (first 10): {linked_data.columns[:10].tolist()}\")\n", "print(f\"Trait column exists: {trait in linked_data.columns}\")\n", "\n", "# 4. Handle missing values in the linked data\n", "linked_data = handle_missing_values(linked_data, trait)\n", "print(f\"Data after handling missing values: {linked_data.shape}\")\n", "\n", "# 5. Check if trait and demographic features are biased\n", "is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)\n", "\n", "# 6. Conduct final quality validation and save relevant information\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=unbiased_linked_data,\n", " note=\"Dataset contains gene expression data from patients with IBS and IBD, examining transcriptomic responses.\"\n", ")\n", "\n", "# 7. If the linked data is usable, save it as a CSV file\n", "if is_usable:\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " unbiased_linked_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 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 }