{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "76abe0e3", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:13:30.914432Z", "iopub.status.busy": "2025-03-25T07:13:30.914330Z", "iopub.status.idle": "2025-03-25T07:13:31.070838Z", "shell.execute_reply": "2025-03-25T07:13:31.070502Z" } }, "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 = \"GSE63379\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Irritable_bowel_syndrome_(IBS)\"\n", "in_cohort_dir = \"../../input/GEO/Irritable_bowel_syndrome_(IBS)/GSE63379\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Irritable_bowel_syndrome_(IBS)/GSE63379.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Irritable_bowel_syndrome_(IBS)/gene_data/GSE63379.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Irritable_bowel_syndrome_(IBS)/clinical_data/GSE63379.csv\"\n", "json_path = \"../../output/preprocess/Irritable_bowel_syndrome_(IBS)/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "dafa77ca", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "d0157883", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:13:31.072175Z", "iopub.status.busy": "2025-03-25T07:13:31.072043Z", "iopub.status.idle": "2025-03-25T07:13:31.219066Z", "shell.execute_reply": "2025-03-25T07:13:31.218732Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Genome-wide Expression Profiling in Irritable Bowel Syndrome\"\n", "!Series_summary\t\"Differential gene expression profiling in peripheral blood mononuclear cells (PBMCs) was performed using Human Transcriptome Array 2 (HTA2)\"\n", "!Series_overall_design\t\"Expression profiles of peripheral blood mononuclear cell (PBMCs) from 35 IBS samples and 32 healthy control was assessed.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['disease status: healthy', 'disease status: IBS'], 1: ['tissue: blood'], 2: ['cell type: peripheral blood mononuclear cells']}\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": "41e878ba", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "f13b4405", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:13:31.220677Z", "iopub.status.busy": "2025-03-25T07:13:31.220572Z", "iopub.status.idle": "2025-03-25T07:13:31.224739Z", "shell.execute_reply": "2025-03-25T07:13:31.224464Z" } }, "outputs": [], "source": [ "# 1. Gene Expression Data Availability\n", "# Based on series summary and design, this dataset contains gene expression data from PBMCs using HTA2 array\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "# For trait (IBS status): available in row 0\n", "trait_row = 0\n", "# No age data available\n", "age_row = None\n", "# No gender data available\n", "gender_row = None\n", "\n", "# 2.2 Data Type Conversion\n", "def convert_trait(value):\n", " \"\"\"Convert IBS status to binary: 1 for IBS, 0 for healthy control\"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract value after colon if exists\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " if value.lower() == 'ibs':\n", " return 1\n", " elif value.lower() == 'healthy':\n", " return 0\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age to float\"\"\"\n", " # Not applicable as age data is not available\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender to binary: 1 for male, 0 for female\"\"\"\n", " # Not applicable as 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", "# 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", "# Since trait_row is not None, we need to extract clinical features\n", "if trait_row is not None:\n", " # Read clinical data\n", " clinical_data_file = os.path.join(in_cohort_dir, \"clinical_data.csv\")\n", " if os.path.exists(clinical_data_file):\n", " clinical_data = pd.read_csv(clinical_data_file)\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 dataframe\n", " preview = preview_df(selected_clinical_df)\n", " print(\"Preview of clinical data:\")\n", " print(preview)\n", " \n", " # Save 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, index=False)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "65b98bb1", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "84147b75", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:13:31.226258Z", "iopub.status.busy": "2025-03-25T07:13:31.226154Z", "iopub.status.idle": "2025-03-25T07:13:31.467844Z", "shell.execute_reply": "2025-03-25T07:13:31.467481Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Found data marker at line 58\n", "Header line: \"ID_REF\"\t\"GSM1547708\"\t\"GSM1547709\"\t\"GSM1547710\"\t\"GSM1547711\"\t\"GSM1547712\"\t\"GSM1547713\"\t\"GSM1547714\"\t\"GSM1547715\"\t\"GSM1547716\"\t\"GSM1547717\"\t\"GSM1547718\"\t\"GSM1547719\"\t\"GSM1547720\"\t\"GSM1547721\"\t\"GSM1547722\"\t\"GSM1547723\"\t\"GSM1547724\"\t\"GSM1547725\"\t\"GSM1547726\"\t\"GSM1547727\"\t\"GSM1547728\"\t\"GSM1547729\"\t\"GSM1547730\"\t\"GSM1547731\"\t\"GSM1547732\"\t\"GSM1547733\"\t\"GSM1547734\"\t\"GSM1547735\"\t\"GSM1547736\"\t\"GSM1547737\"\t\"GSM1547738\"\t\"GSM1547739\"\t\"GSM1547740\"\t\"GSM1547741\"\t\"GSM1547742\"\t\"GSM1547743\"\t\"GSM1547744\"\t\"GSM1547745\"\t\"GSM1547746\"\t\"GSM1547747\"\t\"GSM1547748\"\t\"GSM1547749\"\t\"GSM1547750\"\t\"GSM1547751\"\t\"GSM1547752\"\t\"GSM1547753\"\t\"GSM1547754\"\t\"GSM1547755\"\t\"GSM1547756\"\t\"GSM1547757\"\t\"GSM1547758\"\t\"GSM1547759\"\t\"GSM1547760\"\t\"GSM1547761\"\t\"GSM1547762\"\t\"GSM1547763\"\t\"GSM1547764\"\t\"GSM1547765\"\t\"GSM1547766\"\t\"GSM1547767\"\t\"GSM1547768\"\t\"GSM1547769\"\t\"GSM1547770\"\t\"GSM1547771\"\t\"GSM1547772\"\t\"GSM1547773\"\t\"GSM1547774\"\n", "First data line: \"2824546_st\"\t11.72\t12.16\t12.45\t11.97\t12.73\t13.05\t12.72\t13.11\t12.02\t12.71\t11.02\t11.93\t12.04\t11.53\t12.12\t12.47\t12.45\t12.04\t11.9\t12.09\t12.02\t11.29\t11.99\t12.26\t12.56\t11.95\t12.77\t12.68\t12.11\t12.05\t13.03\t12.77\t12.83\t12.73\t11.93\t12.67\t12.39\t12.05\t12.72\t12.56\t11.97\t12.4\t12.43\t12.24\t12.33\t12.19\t12.4\t12.45\t12.52\t12.65\t12.15\t12.59\t12.22\t12.09\t12.79\t12.05\t12.15\t11.86\t12.54\t12.56\t12.47\t12.32\t11.69\t12.67\t11.71\t12.53\t12.65\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Index(['2824546_st', '2824549_st', '2824551_st', '2824554_st', '2827992_st',\n", " '2827995_st', '2827996_st', '2828010_st', '2828012_st', '2835442_st',\n", " '2835447_st', '2835453_st', '2835456_st', '2835459_st', '2835461_st',\n", " '2839509_st', '2839511_st', '2839513_st', '2839515_st', '2839517_st'],\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": "099d8c76", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "e9ce8bfd", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:13:31.469529Z", "iopub.status.busy": "2025-03-25T07:13:31.469418Z", "iopub.status.idle": "2025-03-25T07:13:31.471288Z", "shell.execute_reply": "2025-03-25T07:13:31.471015Z" } }, "outputs": [], "source": [ "# Looking at the gene identifiers in the gene expression data, I can see they follow the format \n", "# like \"2824546_st\", which suggests these are probe IDs from a microarray platform (likely Affymetrix)\n", "# rather than standard human gene symbols.\n", "#\n", "# These identifiers need to be mapped to standard gene symbols for meaningful analysis.\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "71bcc48f", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "bb572f17", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:13:31.472798Z", "iopub.status.busy": "2025-03-25T07:13:31.472689Z", "iopub.status.idle": "2025-03-25T07:13:38.966139Z", "shell.execute_reply": "2025-03-25T07:13:38.965768Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene annotation preview:\n", "{'ID': ['TC01000001.hg.1', 'TC01000002.hg.1', 'TC01000003.hg.1', 'TC01000004.hg.1', 'TC01000005.hg.1'], 'probeset_id': ['TC01000001.hg.1', 'TC01000002.hg.1', 'TC01000003.hg.1', 'TC01000004.hg.1', 'TC01000005.hg.1'], 'seqname': ['chr1', 'chr1', 'chr1', 'chr1', 'chr1'], 'strand': ['+', '+', '+', '+', '+'], 'start': ['11869', '29554', '69091', '160446', '317811'], 'stop': ['14409', '31109', '70008', '161525', '328581'], 'total_probes': [49.0, 60.0, 30.0, 30.0, 191.0], 'gene_assignment': ['NR_046018 // DDX11L1 // DEAD/H (Asp-Glu-Ala-Asp/His) box helicase 11 like 1 // 1p36.33 // 100287102 /// ENST00000456328 // DDX11L5 // DEAD/H (Asp-Glu-Ala-Asp/His) box helicase 11 like 5 // 9p24.3 // 100287596 /// ENST00000456328 // DDX11L1 // DEAD/H (Asp-Glu-Ala-Asp/His) box helicase 11 like 1 // 1p36.33 // 100287102', 'ENST00000408384 // MIR1302-11 // microRNA 1302-11 // --- // 100422919 /// ENST00000408384 // MIR1302-10 // microRNA 1302-10 // --- // 100422834 /// ENST00000408384 // MIR1302-9 // microRNA 1302-9 // --- // 100422831 /// ENST00000408384 // MIR1302-2 // microRNA 1302-2 // --- // 100302278 /// ENST00000469289 // MIR1302-11 // microRNA 1302-11 // --- // 100422919 /// ENST00000469289 // MIR1302-10 // microRNA 1302-10 // --- // 100422834 /// ENST00000469289 // MIR1302-9 // microRNA 1302-9 // --- // 100422831 /// ENST00000469289 // MIR1302-2 // microRNA 1302-2 // --- // 100302278 /// ENST00000473358 // MIR1302-11 // microRNA 1302-11 // --- // 100422919 /// ENST00000473358 // MIR1302-10 // microRNA 1302-10 // --- // 100422834 /// ENST00000473358 // MIR1302-9 // microRNA 1302-9 // --- // 100422831 /// ENST00000473358 // MIR1302-2 // microRNA 1302-2 // --- // 100302278 /// OTTHUMT00000002841 // OTTHUMG00000000959 // NULL // --- // --- /// OTTHUMT00000002841 // RP11-34P13.3 // NULL // --- // --- /// OTTHUMT00000002840 // OTTHUMG00000000959 // NULL // --- // --- /// OTTHUMT00000002840 // RP11-34P13.3 // NULL // --- // ---', 'NM_001005484 // OR4F5 // olfactory receptor, family 4, subfamily F, member 5 // 1p36.33 // 79501 /// ENST00000335137 // OR4F5 // olfactory receptor, family 4, subfamily F, member 5 // 1p36.33 // 79501 /// OTTHUMT00000003223 // OR4F5 // NULL // --- // ---', 'OTTHUMT00000007169 // OTTHUMG00000002525 // NULL // --- // --- /// OTTHUMT00000007169 // RP11-34P13.9 // NULL // --- // ---', 'NR_028322 // LOC100132287 // uncharacterized LOC100132287 // 1p36.33 // 100132287 /// NR_028327 // LOC100133331 // uncharacterized LOC100133331 // 1p36.33 // 100133331 /// ENST00000425496 // LOC101060495 // uncharacterized LOC101060495 // --- // 101060495 /// ENST00000425496 // LOC101060494 // uncharacterized LOC101060494 // --- // 101060494 /// ENST00000425496 // LOC101059936 // uncharacterized LOC101059936 // --- // 101059936 /// ENST00000425496 // LOC100996502 // uncharacterized LOC100996502 // --- // 100996502 /// ENST00000425496 // LOC100996328 // uncharacterized LOC100996328 // --- // 100996328 /// ENST00000425496 // LOC100287894 // uncharacterized LOC100287894 // 7q11.21 // 100287894 /// NR_028325 // LOC100132062 // uncharacterized LOC100132062 // 5q35.3 // 100132062 /// OTTHUMT00000346878 // OTTHUMG00000156968 // NULL // --- // --- /// OTTHUMT00000346878 // RP4-669L17.10 // NULL // --- // --- /// OTTHUMT00000346879 // OTTHUMG00000156968 // NULL // --- // --- /// OTTHUMT00000346879 // RP4-669L17.10 // NULL // --- // --- /// OTTHUMT00000346880 // OTTHUMG00000156968 // NULL // --- // --- /// OTTHUMT00000346880 // RP4-669L17.10 // NULL // --- // --- /// OTTHUMT00000346881 // OTTHUMG00000156968 // NULL // --- // --- /// OTTHUMT00000346881 // RP4-669L17.10 // NULL // --- // ---'], 'mrna_assignment': ['NR_046018 // RefSeq // Homo sapiens DEAD/H (Asp-Glu-Ala-Asp/His) box helicase 11 like 1 (DDX11L1), non-coding RNA. // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000456328 // ENSEMBL // cdna:known chromosome:GRCh37:1:11869:14409:1 gene:ENSG00000223972 gene_biotype:pseudogene transcript_biotype:processed_transcript // chr1 // 100 // 100 // 0 // --- // 0 /// uc001aaa.3 // UCSC Genes // --- // chr1 // 100 // 100 // 0 // --- // 0 /// uc010nxq.1 // UCSC Genes // --- // chr1 // 100 // 100 // 0 // --- // 0 /// uc010nxr.1 // UCSC Genes // --- // chr1 // 100 // 100 // 0 // --- // 0', 'ENST00000408384 // ENSEMBL // ncrna:miRNA chromosome:GRCh37:1:30366:30503:1 gene:ENSG00000221311 gene_biotype:miRNA transcript_biotype:miRNA // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000469289 // ENSEMBL // havana:lincRNA chromosome:GRCh37:1:30267:31109:1 gene:ENSG00000243485 gene_biotype:lincRNA transcript_biotype:lincRNA // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000473358 // ENSEMBL // havana:lincRNA chromosome:GRCh37:1:29554:31097:1 gene:ENSG00000243485 gene_biotype:lincRNA transcript_biotype:lincRNA // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000002841 // Havana transcript // cdna:all chromosome:VEGA52:1:30267:31109:1 Gene:OTTHUMG00000000959 // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000002840 // Havana transcript // cdna:all chromosome:VEGA52:1:29554:31097:1 Gene:OTTHUMG00000000959 // chr1 // 100 // 100 // 0 // --- // 0', 'NM_001005484 // RefSeq // Homo sapiens olfactory receptor, family 4, subfamily F, member 5 (OR4F5), mRNA. // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000335137 // ENSEMBL // cdna:known chromosome:GRCh37:1:69091:70008:1 gene:ENSG00000186092 gene_biotype:protein_coding transcript_biotype:protein_coding // chr1 // 100 // 100 // 0 // --- // 0 /// uc001aal.1 // UCSC Genes // --- // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000003223 // Havana transcript // cdna:all chromosome:VEGA52:1:69091:70008:1 Gene:OTTHUMG00000001094 // chr1 // 100 // 100 // 0 // --- // 0', 'ENST00000496488 // ENSEMBL // havana:lincRNA chromosome:GRCh37:1:160446:161525:1 gene:ENSG00000241599 gene_biotype:lincRNA transcript_biotype:lincRNA // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000007169 // Havana transcript // cdna:all chromosome:VEGA52:1:160446:161525:1 Gene:OTTHUMG00000002525 // chr1 // 100 // 100 // 0 // --- // 0', 'NR_028322 // RefSeq // Homo sapiens uncharacterized LOC100132287 (LOC100132287), non-coding RNA. // chr1 // 100 // 100 // 0 // --- // 0 /// NR_028327 // RefSeq // Homo sapiens uncharacterized LOC100133331 (LOC100133331), non-coding RNA. // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000425496 // ENSEMBL // ensembl:lincRNA chromosome:GRCh37:1:324756:328453:1 gene:ENSG00000237094 gene_biotype:lincRNA transcript_biotype:lincRNA // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000426316 // ENSEMBL // [retired] cdna:known chromosome:GRCh37:1:317811:328455:1 gene:ENSG00000240876 gene_biotype:processed_transcript transcript_biotype:processed_transcript // chr1 // 100 // 100 // 0 // --- // 0 /// NR_028325 // RefSeq // Homo sapiens uncharacterized LOC100132062 (LOC100132062), non-coding RNA. // chr1 // 100 // 100 // 0 // --- // 0 /// uc009vjk.2 // UCSC Genes // --- // chr1 // 100 // 100 // 0 // --- // 0 /// uc021oeh.1 // UCSC Genes // --- // chr1 // 100 // 100 // 0 // --- // 0 /// uc021oei.1 // UCSC Genes // --- // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000346906 // Havana transcript // [retired] cdna:all chromosome:VEGA50:1:317811:328455:1 Gene:OTTHUMG00000156972 // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000346878 // Havana transcript // cdna:all chromosome:VEGA52:1:320162:321056:1 Gene:OTTHUMG00000156968 // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000346879 // Havana transcript // cdna:all chromosome:VEGA52:1:320162:324461:1 Gene:OTTHUMG00000156968 // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000346880 // Havana transcript // cdna:all chromosome:VEGA52:1:317720:324873:1 Gene:OTTHUMG00000156968 // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000346881 // Havana transcript // cdna:all chromosome:VEGA52:1:322672:324955:1 Gene:OTTHUMG00000156968 // chr1 // 100 // 100 // 0 // --- // 0'], 'swissprot': ['NR_046018 // B7ZGX0 /// NR_046018 // B7ZGX2 /// NR_046018 // B7ZGX7 /// NR_046018 // B7ZGX8 /// ENST00000456328 // B7ZGX0 /// ENST00000456328 // B7ZGX2 /// ENST00000456328 // B7ZGX3 /// ENST00000456328 // B7ZGX7 /// ENST00000456328 // B7ZGX8 /// ENST00000456328 // Q6ZU42', '---', 'NM_001005484 // Q8NH21 /// ENST00000335137 // Q8NH21', '---', 'NR_028325 // B4DYM5 /// NR_028325 // B4E0H4 /// NR_028325 // B4E3X0 /// NR_028325 // B4E3X2 /// NR_028325 // Q6ZQS4'], 'unigene': ['NR_046018 // Hs.714157 // testis| normal| adult /// ENST00000456328 // Hs.719844 // brain| testis| normal /// ENST00000456328 // Hs.714157 // testis| normal| adult /// ENST00000456328 // Hs.618434 // testis| normal', 'ENST00000469289 // Hs.622486 // eye| normal| adult /// ENST00000469289 // Hs.729632 // testis| normal /// ENST00000469289 // Hs.742718 // testis /// ENST00000473358 // Hs.622486 // eye| normal| adult /// ENST00000473358 // Hs.729632 // testis| normal /// ENST00000473358 // Hs.742718 // testis', 'NM_001005484 // Hs.554500 // --- /// ENST00000335137 // Hs.554500 // ---', '---', 'NR_028322 // Hs.446409 // adrenal gland| blood| bone| brain| connective tissue| embryonic tissue| eye| intestine| kidney| larynx| lung| lymph node| mouth| pharynx| placenta| prostate| skin| testis| thymus| thyroid| uterus| bladder carcinoma| chondrosarcoma| colorectal tumor| germ cell tumor| head and neck tumor| kidney tumor| leukemia| lung tumor| normal| primitive neuroectodermal tumor of the CNS| uterine tumor|embryoid body| blastocyst| fetus| neonate| adult /// NR_028327 // Hs.733048 // ascites| bladder| blood| brain| embryonic tissue| eye| intestine| kidney| larynx| liver| lung| mammary gland| mouth| pancreas| placenta| prostate| skin| stomach| testis| thymus| thyroid| trachea| uterus| bladder carcinoma| breast (mammary gland) tumor| colorectal tumor| gastrointestinal tumor| head and neck tumor| kidney tumor| leukemia| liver tumor| lung tumor| normal| pancreatic tumor| prostate cancer| retinoblastoma| skin tumor| soft tissue/muscle tissue tumor| uterine tumor|embryoid body| blastocyst| fetus| adult /// ENST00000425496 // Hs.744556 // mammary gland| normal| adult /// ENST00000425496 // Hs.660700 // eye| placenta| testis| normal| adult /// ENST00000425496 // Hs.518952 // blood| brain| intestine| lung| mammary gland| mouth| muscle| pharynx| placenta| prostate| spleen| testis| thymus| thyroid| trachea| breast (mammary gland) tumor| colorectal tumor| head and neck tumor| leukemia| lung tumor| normal| prostate cancer| fetus| adult /// ENST00000425496 // Hs.742131 // testis| normal| adult /// ENST00000425496 // Hs.636102 // uterus| uterine tumor /// ENST00000425496 // Hs.646112 // brain| intestine| larynx| lung| mouth| prostate| testis| thyroid| colorectal tumor| head and neck tumor| lung tumor| normal| prostate cancer| adult /// ENST00000425496 // Hs.647795 // brain| lung| lung tumor| adult /// ENST00000425496 // Hs.684307 // --- /// ENST00000425496 // Hs.720881 // testis| normal /// ENST00000425496 // Hs.729353 // brain| lung| placenta| testis| trachea| lung tumor| normal| fetus| adult /// ENST00000425496 // Hs.735014 // ovary| ovarian tumor /// NR_028325 // Hs.732199 // ascites| blood| brain| connective tissue| embryonic tissue| eye| intestine| kidney| lung| ovary| placenta| prostate| stomach| testis| thymus| uterus| chondrosarcoma| colorectal tumor| gastrointestinal tumor| kidney tumor| leukemia| lung tumor| normal| ovarian tumor| fetus| adult'], 'category': ['main', 'main', 'main', 'main', 'main'], 'locus type': ['Coding', 'Coding', 'Coding', 'Coding', 'Coding'], 'notes': ['---', '---', '---', '---', '2 retired transcript(s) from ENSEMBL, Havana transcript'], 'SPOT_ID': ['chr1(+):11869-14409', 'chr1(+):29554-31109', 'chr1(+):69091-70008', 'chr1(+):160446-161525', 'chr1(+):317811-328581']}\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": "5937706d", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "eb41f9ff", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:13:38.968071Z", "iopub.status.busy": "2025-03-25T07:13:38.967942Z", "iopub.status.idle": "2025-03-25T07:13:45.649366Z", "shell.execute_reply": "2025-03-25T07:13:45.648989Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "First few probe IDs in gene expression data:\n", "Index(['2824546_st', '2824549_st', '2824551_st', '2824554_st', '2827992_st'], dtype='object', name='ID')\n", "\n", "Gene assignment example:\n", "NR_046018 // DDX11L1 // DEAD/H (Asp-Glu-Ala-Asp/His) box helicase 11 like 1 // 1p36.33 // 100287102 /// ENST00000456328 // DDX11L5 // DEAD/H (Asp-Glu-Ala-Asp/His) box helicase 11 like 5 // 9p24.3 // 100287596 /// ENST00000456328 // DDX11L1 // DEAD/H (Asp-Glu-Ala-Asp/His) box helicase 11 like 1 // 1p36.33 // 100287102\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene expression data after mapping (first 5 rows, 5 columns):\n", " GSM1547708 GSM1547709 GSM1547710 GSM1547711 GSM1547712\n", "Gene \n", "A- 18.412500 18.445417 18.259167 18.320000 18.404167\n", "A-2 1.498000 1.492000 1.498000 1.494000 1.482000\n", "A-52 3.243333 3.263333 3.356667 3.276667 3.306667\n", "A-575C2 2.292500 2.227500 2.232500 2.227500 2.235000\n", "A-E 2.121667 2.066667 2.055000 2.073333 2.061667\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data saved to ../../output/preprocess/Irritable_bowel_syndrome_(IBS)/gene_data/GSE63379.csv\n" ] } ], "source": [ "# 1. Identify the columns containing gene IDs and gene symbols\n", "# After examining the gene annotation data, I can see:\n", "# - The probe IDs in the gene expression data end with \"_st\" (e.g., \"2824546_st\")\n", "# - The 'ID' column in annotation contains probe identifiers with a different format (e.g., \"TC01000001.hg.1\")\n", "# - The 'gene_assignment' column contains gene symbol information\n", "\n", "# First, let's look at the format of IDs in the gene expression data vs. annotation data\n", "print(\"First few probe IDs in gene expression data:\")\n", "print(gene_data.index[:5])\n", "\n", "# We need to check if the annotation data's ID is comparable to the gene data's ID format\n", "# Let's compare a small sample\n", "\n", "# Let's inspect the gene_assignment column which likely has gene symbol information\n", "print(\"\\nGene assignment example:\")\n", "print(gene_annotation['gene_assignment'].iloc[0])\n", "\n", "# 2. Create a mapping dataframe with probe IDs and corresponding gene symbols\n", "# Since the IDs don't directly match, we need to find a way to map between them\n", "# Let's check if there's a direct way to map using other columns\n", "\n", "# The gene expression data probes end with \"_st\" which suggests they're from Affymetrix platform\n", "# We need to examine the gene annotation more carefully to find the right columns\n", "\n", "# Extract probe ID and gene symbol mapping\n", "# In this case, we'll use the 'ID' column as the probe ID and extract gene symbols from 'gene_assignment'\n", "mapping_df = pd.DataFrame({'ID': gene_annotation['ID'].astype(str)})\n", "mapping_df['Gene'] = gene_annotation['gene_assignment']\n", "\n", "# 3. Apply gene mapping to convert probe measurements to gene expression values\n", "# This will extract gene symbols from the gene_assignment text and apply the mapping\n", "gene_data = apply_gene_mapping(gene_data, mapping_df)\n", "\n", "# Preview the mapped gene expression data\n", "print(\"\\nGene expression data after mapping (first 5 rows, 5 columns):\")\n", "print(gene_data.iloc[:5, :5])\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": "67cf3a9c", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "c586e929", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:13:45.651407Z", "iopub.status.busy": "2025-03-25T07:13:45.651266Z", "iopub.status.idle": "2025-03-25T07:14:36.232740Z", "shell.execute_reply": "2025-03-25T07:14:36.232180Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Clinical data structure:\n", "{0: ['disease status: healthy', 'disease status: IBS'], 1: ['tissue: blood'], 2: ['cell type: peripheral blood mononuclear cells']}\n", "Corrected clinical data saved to ../../output/preprocess/Irritable_bowel_syndrome_(IBS)/clinical_data/GSE63379.csv\n", "Linked data shape: (67, 71529)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Data after handling missing values: (35, 71529)\n", "Quartiles for 'Irritable_bowel_syndrome_(IBS)':\n", " 25%: 1.0\n", " 50% (Median): 1.0\n", " 75%: 1.0\n", "Min: 1.0\n", "Max: 1.0\n", "The distribution of the feature 'Irritable_bowel_syndrome_(IBS)' in this dataset is severely biased.\n", "\n", "Data was determined to be unusable and was not saved\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 }