{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "1cd2af37", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:14:37.115099Z", "iopub.status.busy": "2025-03-25T07:14:37.114983Z", "iopub.status.idle": "2025-03-25T07:14:37.276513Z", "shell.execute_reply": "2025-03-25T07:14:37.276153Z" } }, "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 = \"GSE66824\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Irritable_bowel_syndrome_(IBS)\"\n", "in_cohort_dir = \"../../input/GEO/Irritable_bowel_syndrome_(IBS)/GSE66824\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Irritable_bowel_syndrome_(IBS)/GSE66824.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Irritable_bowel_syndrome_(IBS)/gene_data/GSE66824.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Irritable_bowel_syndrome_(IBS)/clinical_data/GSE66824.csv\"\n", "json_path = \"../../output/preprocess/Irritable_bowel_syndrome_(IBS)/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "2742c4b0", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "83e476aa", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:14:37.277759Z", "iopub.status.busy": "2025-03-25T07:14:37.277618Z", "iopub.status.idle": "2025-03-25T07:14:37.462837Z", "shell.execute_reply": "2025-03-25T07:14:37.462483Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Genomic and Clinical Effects Associated with a Relaxation Response Mind-Body Intervention in Patients with Irritable Bowel Syndrome and Inflammatory Bowel Disease\"\n", "!Series_summary\t\"Patients with chronic illnesses such as Irritable Bowel Syndrome (IBS) or Inflammatory Bowel Disease (IBD) often have reduced quality of life. IBS is characterized by abdominal pain/discomfort associated with altered bowel function, such as diarrhea or constipation, without gross structural changes or inflammation [1]; IBD is characterized by gross inflammation in the gastrointestinal (GI) tract which can result in symptoms such as abdominal pain, cramping, diarrhea and bloody stools. IBS and IBD can profoundly affect quality of life and are influenced by stress and resiliency.The impact of mind-body interventions (MBIs) on IBS and IBD patients has not previously been examined. In this study IBS and IBD patients were enrolled in a 9-week relaxation response based mind-body group intervention (RR-MBI), focusing on elicitation of the RR and cognitive skill building. We performed Peripheral blood transcriptome analysis to identify genomic correlates of the RR-MBI.\"\n", "!Series_overall_design\t\"This pilot, single center, single-arm, open-label study utilized an RR-MBI for the treatment of IBS and IBD using elicitation of the RR through meditation techniques and cognitive skill building, as established by the Benson-Henry Institute for Mind Body Medicine at the Massachusetts General Hospital (BHI).Blood was collected at baseline and after 9 weeks for transcriptional expression profiling in PAXgene (Qiagen) tubes. Total RNA was isolated from whole blood samples and gene expression profile was assessed on IBS and IBD patients with paired pre- and post-intervention samples using HT U133 Plus PM Array plates (Affymetrix, Santa Clara, CA).\"\n", "Sample Characteristics Dictionary:\n", "{0: ['patient: A01', 'patient: A02', 'patient: A03', 'patient: A06', 'patient: A07', 'patient: A10', 'patient: A13', 'patient: A14', 'patient: A15', 'patient: A16', 'patient: A18', 'patient: A20', 'patient: A23', 'patient: A25', 'patient: B01', 'patient: B03', 'patient: B04', 'patient: B06', 'patient: B07', 'patient: B08', 'patient: B09', 'patient: B11', 'patient: B12', 'patient: B13', 'patient: B14', 'patient: B16', 'patient: B20', 'patient: B22', 'patient: B23', 'patient: B24'], 1: ['disease state: IBS', 'disease state: IBD'], 2: ['time point: baseline before intervention', 'time point: after 9 weeks of intervention', 'time point: before intervention'], 3: ['tissue: peripheral blood'], 4: ['disease state: IBS', 'disease state: IBD'], 5: ['time point: baseline before intervention', 'time point: after 9 weeks of intervention', 'time point: before intervention'], 6: ['tissue: peripheral blood']}\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": "606fd19d", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "82e027a3", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:14:37.464334Z", "iopub.status.busy": "2025-03-25T07:14:37.464222Z", "iopub.status.idle": "2025-03-25T07:14:37.485872Z", "shell.execute_reply": "2025-03-25T07:14:37.485570Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Preview of selected clinical features: {0: [nan], 1: [0.0], 2: [nan], 3: [nan], 4: [0.0], 5: [nan], 6: [nan]}\n", "Clinical data saved to ../../output/preprocess/Irritable_bowel_syndrome_(IBS)/clinical_data/GSE66824.csv\n" ] } ], "source": [ "import pandas as pd\n", "import numpy as np\n", "import os\n", "import json\n", "from typing import Optional, Callable, Dict, Any, List\n", "\n", "# 1. Gene Expression Data Availability\n", "# Based on the background information, there is transcriptome analysis using Affymetrix arrays\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "\n", "# For trait (IBS/IBD):\n", "# From sample characteristics, key 1 and 4 both contain disease state information\n", "trait_row = 1 # Using the first occurrence\n", "\n", "# For age:\n", "# No age information is available in the sample characteristics\n", "age_row = None\n", "\n", "# For gender:\n", "# No gender information is available in the sample characteristics\n", "gender_row = None\n", "\n", "# 2.2 Data Type Conversion Functions\n", "\n", "def convert_trait(value: str) -> int:\n", " \"\"\"Convert trait value to binary (0 for IBD, 1 for IBS)\"\"\"\n", " if pd.isna(value):\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 \"IBS\" in value:\n", " return 1 # IBS is our target trait\n", " elif \"IBD\" in value:\n", " return 0 # IBD is the control\n", " else:\n", " return None\n", "\n", "def convert_age(value: str) -> Optional[float]:\n", " \"\"\"Convert age value to float\"\"\"\n", " # Not used since age data is not available\n", " return None\n", "\n", "def convert_gender(value: str) -> Optional[int]:\n", " \"\"\"Convert gender value to binary (0 for female, 1 for male)\"\"\"\n", " # Not used since gender data is not available\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Determine trait data availability\n", "is_trait_available = trait_row is not None\n", "\n", "# Validate and record cohort info\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", "# Only execute if trait data is available\n", "if trait_row is not None:\n", " # Create a DataFrame from the sample characteristics for clinical data extraction\n", " sample_char_dict = {0: ['patient: A01', 'patient: A02', 'patient: A03', 'patient: A06', 'patient: A07', 'patient: A10', 'patient: A13', 'patient: A14', 'patient: A15', 'patient: A16', 'patient: A18', 'patient: A20', 'patient: A23', 'patient: A25', 'patient: B01', 'patient: B03', 'patient: B04', 'patient: B06', 'patient: B07', 'patient: B08', 'patient: B09', 'patient: B11', 'patient: B12', 'patient: B13', 'patient: B14', 'patient: B16', 'patient: B20', 'patient: B22', 'patient: B23', 'patient: B24'], \n", " 1: ['disease state: IBS', 'disease state: IBD'], \n", " 2: ['time point: baseline before intervention', 'time point: after 9 weeks of intervention', 'time point: before intervention'], \n", " 3: ['tissue: peripheral blood'], \n", " 4: ['disease state: IBS', 'disease state: IBD'], \n", " 5: ['time point: baseline before intervention', 'time point: after 9 weeks of intervention', 'time point: before intervention'], \n", " 6: ['tissue: peripheral blood']}\n", " \n", " clinical_data = pd.DataFrame()\n", " \n", " # Add each row from the sample characteristics dictionary as a column\n", " for key, values in sample_char_dict.items():\n", " clinical_data[key] = values if len(values) == len(clinical_data) else values + [None] * (len(clinical_data) - len(values))\n", " \n", " # Extract clinical features\n", " selected_clinical_df = geo_select_clinical_features(\n", " clinical_df=clinical_data,\n", " trait=trait,\n", " trait_row=trait_row,\n", " convert_trait=convert_trait,\n", " age_row=age_row,\n", " convert_age=convert_age,\n", " gender_row=gender_row,\n", " convert_gender=convert_gender\n", " )\n", " \n", " # Preview the data\n", " preview = preview_df(selected_clinical_df)\n", " print(f\"Preview of selected clinical features: {preview}\")\n", " \n", " # Create directory if it doesn't exist\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " \n", " # Save the clinical data\n", " selected_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": "df418d0f", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "ad60cfcc", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:14:37.487231Z", "iopub.status.busy": "2025-03-25T07:14:37.487123Z", "iopub.status.idle": "2025-03-25T07:14:37.776925Z", "shell.execute_reply": "2025-03-25T07:14:37.776538Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Found data marker at line 69\n", "Header line: \"ID_REF\"\t\"GSM1632703\"\t\"GSM1632704\"\t\"GSM1632705\"\t\"GSM1632706\"\t\"GSM1632707\"\t\"GSM1632708\"\t\"GSM1632709\"\t\"GSM1632710\"\t\"GSM1632711\"\t\"GSM1632712\"\t\"GSM1632713\"\t\"GSM1632714\"\t\"GSM1632715\"\t\"GSM1632716\"\t\"GSM1632717\"\t\"GSM1632718\"\t\"GSM1632719\"\t\"GSM1632720\"\t\"GSM1632721\"\t\"GSM1632722\"\t\"GSM1632723\"\t\"GSM1632724\"\t\"GSM1632725\"\t\"GSM1632726\"\t\"GSM1632727\"\t\"GSM1632728\"\t\"GSM1632729\"\t\"GSM1632730\"\t\"GSM1632731\"\t\"GSM1632732\"\t\"GSM1632733\"\t\"GSM1632734\"\t\"GSM1632735\"\t\"GSM1632736\"\t\"GSM1632737\"\t\"GSM1632738\"\t\"GSM1632739\"\t\"GSM1632740\"\t\"GSM1632741\"\t\"GSM1632742\"\t\"GSM1632743\"\t\"GSM1632744\"\t\"GSM1632745\"\t\"GSM1632746\"\t\"GSM1632747\"\t\"GSM1632748\"\t\"GSM1632749\"\t\"GSM1632750\"\t\"GSM1632751\"\t\"GSM1632752\"\t\"GSM1632753\"\t\"GSM1632754\"\t\"GSM1632755\"\t\"GSM1632756\"\t\"GSM1632757\"\t\"GSM1632758\"\t\"GSM1632759\"\t\"GSM1632760\"\t\"GSM1632761\"\t\"GSM1632762\"\t\"GSM1632763\"\t\"GSM1632764\"\t\"GSM1632765\"\t\"GSM1632766\"\t\"GSM1632767\"\t\"GSM1632768\"\n", "First data line: \"1007_PM_s_at\"\t5.84456\t6.18582\t5.95226\t6.27915\t5.99674\t5.9074\t6.1111\t6.12754\t7.28588\t6.72427\t6.53747\t6.67556\t5.95098\t6.41456\t6.41504\t6.41263\t6.0871\t5.9633\t6.20626\t6.36869\t5.94319\t6.27728\t5.49023\t6.13201\t6.40264\t5.25964\t5.91883\t5.87057\t7.12873\t6.43177\t5.22649\t5.69167\t5.78122\t5.54628\t6.0303\t5.78549\t5.7858\t6.1731\t5.74382\t5.65893\t6.82497\t6.28689\t6.15711\t6.52642\t5.5559\t6.37665\t6.65781\t6.78156\t5.43852\t5.66046\t6.54079\t6.58529\t5.62203\t6.03496\t5.49261\t5.50555\t6.03109\t6.2762\t5.64033\t6.08245\t5.5885\t5.12451\t5.7729\t5.7258\t5.87228\t6.05477\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Index(['1007_PM_s_at', '1053_PM_at', '117_PM_at', '121_PM_at', '1255_PM_g_at',\n", " '1294_PM_at', '1316_PM_at', '1320_PM_at', '1405_PM_i_at', '1431_PM_at',\n", " '1438_PM_at', '1487_PM_at', '1494_PM_f_at', '1552256_PM_a_at',\n", " '1552257_PM_a_at', '1552258_PM_at', '1552261_PM_at', '1552263_PM_at',\n", " '1552264_PM_a_at', '1552266_PM_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": "a0b9f0cf", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "eb0c7c16", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:14:37.778340Z", "iopub.status.busy": "2025-03-25T07:14:37.778228Z", "iopub.status.idle": "2025-03-25T07:14:37.780130Z", "shell.execute_reply": "2025-03-25T07:14:37.779836Z" } }, "outputs": [], "source": [ "# Based on the gene identifiers shown (like \"1007_PM_s_at\", \"1053_PM_at\", etc.), \n", "# these appear to be Affymetrix probe IDs from a microarray platform.\n", "# These are not standard human gene symbols and will need to be mapped to gene symbols.\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "1ab5a3ba", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "0313bb61", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:14:37.781458Z", "iopub.status.busy": "2025-03-25T07:14:37.781355Z", "iopub.status.idle": "2025-03-25T07:14:43.117259Z", "shell.execute_reply": "2025-03-25T07:14:43.116865Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene annotation preview:\n", "{'ID': ['1007_PM_s_at', '1053_PM_at', '117_PM_at', '121_PM_at', '1255_PM_g_at'], 'GB_ACC': ['U48705', 'M87338', 'X51757', 'X69699', 'L36861'], 'SPOT_ID': [nan, nan, nan, nan, nan], 'Species Scientific Name': ['Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens'], 'Annotation Date': ['Aug 20, 2010', 'Aug 20, 2010', 'Aug 20, 2010', 'Aug 20, 2010', 'Aug 20, 2010'], 'Sequence Type': ['Exemplar sequence', 'Exemplar sequence', 'Exemplar sequence', 'Exemplar sequence', 'Exemplar sequence'], 'Sequence Source': ['Affymetrix Proprietary Database', 'GenBank', 'Affymetrix Proprietary Database', 'GenBank', 'Affymetrix Proprietary Database'], 'Target Description': ['U48705 /FEATURE=mRNA /DEFINITION=HSU48705 Human receptor tyrosine kinase DDR gene, complete cds', 'M87338 /FEATURE= /DEFINITION=HUMA1SBU Human replication factor C, 40-kDa subunit (A1) mRNA, complete cds', \"X51757 /FEATURE=cds /DEFINITION=HSP70B Human heat-shock protein HSP70B' gene\", 'X69699 /FEATURE= /DEFINITION=HSPAX8A H.sapiens Pax8 mRNA', 'L36861 /FEATURE=expanded_cds /DEFINITION=HUMGCAPB Homo sapiens guanylate cyclase activating protein (GCAP) gene exons 1-4, complete cds'], 'Representative Public ID': ['U48705', 'M87338', 'X51757', 'X69699', 'L36861'], 'Gene Title': ['discoidin domain receptor tyrosine kinase 1', 'replication factor C (activator 1) 2, 40kDa', \"heat shock 70kDa protein 6 (HSP70B')\", 'paired box 8', 'guanylate cyclase activator 1A (retina)'], 'Gene Symbol': ['DDR1', 'RFC2', 'HSPA6', 'PAX8', 'GUCA1A'], 'ENTREZ_GENE_ID': ['780', '5982', '3310', '7849', '2978'], 'RefSeq Transcript ID': ['NM_001954 /// NM_013993 /// NM_013994', 'NM_002914 /// NM_181471', 'NM_002155', 'NM_003466 /// NM_013951 /// NM_013952 /// NM_013953 /// NM_013992', 'NM_000409'], 'Gene Ontology Biological Process': ['0001558 // regulation of cell growth // inferred from electronic annotation /// 0001952 // regulation of cell-matrix adhesion // inferred from electronic annotation /// 0006468 // protein amino acid phosphorylation // inferred from electronic annotation /// 0007155 // cell adhesion // inferred from electronic annotation /// 0007155 // cell adhesion // traceable author statement /// 0007169 // transmembrane receptor protein tyrosine kinase signaling pathway // inferred from electronic annotation /// 0007566 // embryo implantation // inferred from electronic annotation /// 0008285 // negative regulation of cell proliferation // inferred from electronic annotation /// 0018108 // peptidyl-tyrosine phosphorylation // inferred from electronic annotation /// 0031100 // organ regeneration // inferred from electronic annotation /// 0043583 // ear development // inferred from electronic annotation /// 0043588 // skin development // inferred from electronic annotation /// 0051789 // response to protein stimulus // inferred from electronic annotation /// 0060444 // branching involved in mammary gland duct morphogenesis // inferred from electronic annotation /// 0060749 // mammary gland alveolus development // inferred from electronic annotation', '0006260 // DNA replication // not recorded /// 0006260 // DNA replication // inferred from electronic annotation /// 0006297 // nucleotide-excision repair, DNA gap filling // not recorded /// 0015979 // photosynthesis // inferred from electronic annotation /// 0015995 // chlorophyll biosynthetic process // inferred from electronic annotation', '0006950 // response to stress // inferred from electronic annotation /// 0006986 // response to unfolded protein // traceable author statement', '0001656 // metanephros development // inferred from electronic annotation /// 0006350 // transcription // inferred from electronic annotation /// 0007275 // multicellular organismal development // inferred from electronic annotation /// 0009653 // anatomical structure morphogenesis // traceable author statement /// 0030154 // cell differentiation // inferred from electronic annotation /// 0030878 // thyroid gland development // inferred from electronic annotation /// 0045449 // regulation of transcription // inferred from electronic annotation /// 0045893 // positive regulation of transcription, DNA-dependent // inferred from sequence or structural similarity /// 0045893 // positive regulation of transcription, DNA-dependent // inferred from direct assay /// 0045944 // positive regulation of transcription from RNA polymerase II promoter // inferred from electronic annotation', '0007165 // signal transduction // non-traceable author statement /// 0007601 // visual perception // inferred from electronic annotation /// 0007601 // visual perception // traceable author statement /// 0007602 // phototransduction // inferred from electronic annotation /// 0031282 // regulation of guanylate cyclase activity // inferred from electronic annotation /// 0050896 // response to stimulus // inferred from electronic annotation'], 'Gene Ontology Cellular Component': ['0005576 // extracellular region // inferred from electronic annotation /// 0005886 // plasma membrane // inferred from electronic annotation /// 0005887 // integral to plasma membrane // traceable author statement /// 0016020 // membrane // inferred from electronic annotation /// 0016021 // integral to membrane // inferred from electronic annotation /// 0016323 // basolateral plasma membrane // inferred from electronic annotation', '0005634 // nucleus // inferred from electronic annotation /// 0005654 // nucleoplasm // not recorded /// 0005663 // DNA replication factor C complex // inferred from direct assay /// 0005663 // DNA replication factor C complex // inferred from electronic annotation', nan, '0005634 // nucleus // inferred from electronic annotation /// 0005654 // nucleoplasm // inferred from sequence or structural similarity /// 0005654 // nucleoplasm // inferred from electronic annotation', '0016020 // membrane // inferred from electronic annotation'], 'Gene Ontology Molecular Function': ['0000166 // nucleotide binding // inferred from electronic annotation /// 0004672 // protein kinase activity // inferred from electronic annotation /// 0004713 // protein tyrosine kinase activity // inferred from electronic annotation /// 0004714 // transmembrane receptor protein tyrosine kinase activity // inferred from electronic annotation /// 0004714 // transmembrane receptor protein tyrosine kinase activity // traceable author statement /// 0004872 // receptor activity // inferred from electronic annotation /// 0005515 // protein binding // inferred from physical interaction /// 0005515 // protein binding // inferred from electronic annotation /// 0005524 // ATP binding // inferred from electronic annotation /// 0016301 // kinase activity // inferred from electronic annotation /// 0016740 // transferase activity // inferred from electronic annotation', '0000166 // nucleotide binding // inferred from electronic annotation /// 0003677 // DNA binding // inferred from electronic annotation /// 0003689 // DNA clamp loader activity // inferred from electronic annotation /// 0005515 // protein binding // inferred from physical interaction /// 0005524 // ATP binding // inferred from electronic annotation /// 0005524 // ATP binding // traceable author statement /// 0016851 // magnesium chelatase activity // inferred from electronic annotation /// 0017111 // nucleoside-triphosphatase activity // inferred from electronic annotation', '0000166 // nucleotide binding // inferred from electronic annotation /// 0005524 // ATP binding // inferred from electronic annotation', '0003677 // DNA binding // inferred from direct assay /// 0003677 // DNA binding // inferred from electronic annotation /// 0003700 // transcription factor activity // traceable author statement /// 0004996 // thyroid-stimulating hormone receptor activity // traceable author statement /// 0005515 // protein binding // inferred from sequence or structural similarity /// 0005515 // protein binding // inferred from electronic annotation /// 0005515 // protein binding // inferred from physical interaction /// 0016563 // transcription activator activity // inferred from sequence or structural similarity /// 0016563 // transcription activator activity // inferred from direct assay /// 0016563 // transcription activator activity // inferred from electronic annotation /// 0043565 // sequence-specific DNA binding // inferred from electronic annotation', '0005509 // calcium ion binding // inferred from electronic annotation /// 0008048 // calcium sensitive guanylate cyclase activator activity // traceable author statement /// 0008048 // calcium sensitive guanylate cyclase activator activity // inferred from electronic annotation /// 0030249 // guanylate cyclase regulator activity // inferred from electronic annotation']}\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": "a4f074fa", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "2c618f06", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:14:43.119059Z", "iopub.status.busy": "2025-03-25T07:14:43.118859Z", "iopub.status.idle": "2025-03-25T07:14:44.089786Z", "shell.execute_reply": "2025-03-25T07:14:44.089342Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Number of genes after mapping: 18989\n", "Sample of gene expression data (first 5 genes, first 3 samples):\n", " GSM1632703 GSM1632704 GSM1632705\n", "Gene \n", "A1BG 3.71206 4.07512 4.23269\n", "A1CF 3.78140 3.36702 2.83565\n", "A2BP1 17.62408 13.62811 13.40417\n", "A2LD1 5.86426 7.02061 7.64654\n", "A2M 10.69333 10.46429 10.85364\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data saved to ../../output/preprocess/Irritable_bowel_syndrome_(IBS)/gene_data/GSE66824.csv\n" ] } ], "source": [ "# 1. Determine the column names for gene identifiers and gene symbols\n", "# From the previous output, we can see:\n", "# - \"ID\" column contains the probe identifiers matching those in the gene expression data\n", "# - \"Gene Symbol\" column contains the human gene symbols we need to map to\n", "\n", "# 2. Get a gene mapping dataframe\n", "# Extract the two relevant columns from the gene annotation dataframe\n", "mapping_df = get_gene_mapping(gene_annotation, prob_col=\"ID\", gene_col=\"Gene Symbol\")\n", "\n", "# 3. Apply gene mapping to convert probe-level measurements to gene expression data\n", "# This divides expression values for probes mapping to multiple genes and sums values for the same gene\n", "gene_data = apply_gene_mapping(gene_data, mapping_df)\n", "\n", "# Display information about the resulting gene expression data\n", "print(f\"Number of genes after mapping: {len(gene_data)}\")\n", "print(f\"Sample of gene expression data (first 5 genes, first 3 samples):\")\n", "print(gene_data.iloc[:5, :3])\n", "\n", "# Save the gene expression data to the output 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": "26903735", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "4620f567", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:14:44.091714Z", "iopub.status.busy": "2025-03-25T07:14:44.091565Z", "iopub.status.idle": "2025-03-25T07:14:54.334215Z", "shell.execute_reply": "2025-03-25T07:14:54.333675Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Clinical data structure:\n", "{0: ['patient: A01', 'patient: A02', 'patient: A03', 'patient: A06', 'patient: A07', 'patient: A10', 'patient: A13', 'patient: A14', 'patient: A15', 'patient: A16', 'patient: A18', 'patient: A20', 'patient: A23', 'patient: A25', 'patient: B01', 'patient: B03', 'patient: B04', 'patient: B06', 'patient: B07', 'patient: B08', 'patient: B09', 'patient: B11', 'patient: B12', 'patient: B13', 'patient: B14', 'patient: B16', 'patient: B20', 'patient: B22', 'patient: B23', 'patient: B24'], 1: ['disease state: IBS', 'disease state: IBD'], 2: ['time point: baseline before intervention', 'time point: after 9 weeks of intervention', 'time point: before intervention'], 3: ['tissue: peripheral blood'], 4: ['disease state: IBS', 'disease state: IBD'], 5: ['time point: baseline before intervention', 'time point: after 9 weeks of intervention', 'time point: before intervention'], 6: ['tissue: peripheral blood']}\n", "Corrected clinical data saved to ../../output/preprocess/Irritable_bowel_syndrome_(IBS)/clinical_data/GSE66824.csv\n", "Linked data shape: (66, 18990)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Data after handling missing values: (66, 18990)\n", "For the feature 'Irritable_bowel_syndrome_(IBS)', the least common label is '1' with 28 occurrences. This represents 42.42% 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)/GSE66824.csv\n" ] } ], "source": [ "# 1. Load the normalized gene data \n", "gene_data = pd.read_csv(out_gene_data_file, index_col=0)\n", "\n", "# 2. Re-extract clinical features from the SOFT file to get proper clinical data\n", "# Use the actual clinical data from the matrix file properly\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "background_info, clinical_data = get_background_and_clinical_data(matrix_file)\n", "\n", "# 3. Create a correct clinical features dataframe\n", "# First inspect what's in the clinical data\n", "clinical_data_dict = get_unique_values_by_row(clinical_data)\n", "print(\"Clinical data structure:\")\n", "print(clinical_data_dict)\n", "\n", "# Based on the sample characteristics dictionary shown previously, \n", "# extract and process clinical features\n", "selected_clinical_df = pd.DataFrame()\n", "\n", "# Process disease state row manually to ensure correct mapping\n", "disease_row = clinical_data.iloc[trait_row]\n", "samples = [col for col in disease_row.index if col != \"!Sample_geo_accession\"]\n", "trait_values = []\n", "\n", "for sample in samples:\n", " value = disease_row[sample]\n", " if pd.isna(value):\n", " trait_values.append(None)\n", " else:\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " if \"IBS\" in value:\n", " trait_values.append(1) # IBS is our target trait\n", " elif \"IBD\" in value:\n", " trait_values.append(0) # IBD is the control\n", " else:\n", " trait_values.append(None)\n", "\n", "# Create dataframe with processed values\n", "selected_clinical_df[trait] = trait_values\n", "selected_clinical_df.index = samples\n", "\n", "# Save the corrected clinical data\n", "os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", "selected_clinical_df.to_csv(out_clinical_data_file)\n", "print(f\"Corrected clinical data saved to {out_clinical_data_file}\")\n", "\n", "# 4. Link the clinical and genetic data\n", "linked_data = pd.DataFrame()\n", "# Transpose gene data to have samples as rows and genes as columns\n", "gene_data_t = gene_data.T\n", "# Verify alignment of sample IDs between clinical and gene data\n", "common_samples = list(set(selected_clinical_df.index) & set(gene_data_t.index))\n", "if common_samples:\n", " gene_data_filtered = gene_data_t.loc[common_samples]\n", " clinical_data_filtered = selected_clinical_df.loc[common_samples]\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", "else:\n", " # Alternative linking approach if sample IDs don't directly match\n", " print(\"No common sample IDs found. Attempting alternative linking...\")\n", " # The GSM ids in gene data columns may correspond to the sample IDs\n", " clinical_data_reset = selected_clinical_df.reset_index()\n", " clinical_data_reset.columns = [\"Sample\"] + list(clinical_data_reset.columns[1:])\n", " gene_data_cols = list(gene_data.columns)\n", " \n", " # Create merged dataframe\n", " data_dict = {trait: []}\n", " # Add trait values\n", " for col in gene_data_cols:\n", " sample_idx = clinical_data_reset.index[clinical_data_reset[\"Sample\"] == col] if \"Sample\" in clinical_data_reset.columns else []\n", " if len(sample_idx) > 0:\n", " data_dict[trait].append(clinical_data_reset.loc[sample_idx[0], trait])\n", " else:\n", " data_dict[trait].append(None)\n", " \n", " # Add gene expression values\n", " for gene in gene_data.index:\n", " data_dict[gene] = list(gene_data.loc[gene])\n", " \n", " linked_data = pd.DataFrame(data_dict, index=gene_data_cols)\n", " print(f\"Alternative linked data shape: {linked_data.shape}\")\n", "\n", "# 5. 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", "# 6. Determine whether the trait and some demographic features are severely biased\n", "is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)\n", "\n", "# 7. Conduct quality check and save the cohort 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 effects of relaxation response mind-body intervention.\"\n", ")\n", "\n", "# 8. 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 }