{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "d2cad7e6", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:01:30.977416Z", "iopub.status.busy": "2025-03-25T08:01:30.976878Z", "iopub.status.idle": "2025-03-25T08:01:31.147285Z", "shell.execute_reply": "2025-03-25T08:01:31.146925Z" } }, "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 = \"Celiac_Disease\"\n", "cohort = \"GSE20332\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Celiac_Disease\"\n", "in_cohort_dir = \"../../input/GEO/Celiac_Disease/GSE20332\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Celiac_Disease/GSE20332.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Celiac_Disease/gene_data/GSE20332.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Celiac_Disease/clinical_data/GSE20332.csv\"\n", "json_path = \"../../output/preprocess/Celiac_Disease/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "c1bb8a8b", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "8964787a", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:01:31.148766Z", "iopub.status.busy": "2025-03-25T08:01:31.148612Z", "iopub.status.idle": "2025-03-25T08:01:31.355242Z", "shell.execute_reply": "2025-03-25T08:01:31.354863Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Primary human leukocyte RNA expression of unrelated Dutch and UK individuals\"\n", "!Series_summary\t\"Multiple common variants for celiac disease influencing immune gene expression\"\n", "!Series_summary\t\"The goal of this study was to study the effect of genetic variation on gene expression of untouched primary leucocytes.\"\n", "!Series_summary\t\"We obtained peripheral blood RNA from unrelated Dutch and UK individuals using PAXgene tubes.\"\n", "!Series_summary\t\"We performed a second-generation genome wide association study of 4,533 celiac disease cases and 10,750 controls. We genotyped 113 selected SNPs with PGWAS<10-4, and 18 SNPs from 14 known loci, in a further 4,918 cases and 5,684 controls. Variants from 13 new regions reached genome wide significance (Pcombined<5x10-8), most contain immune function genes (BACH2, CCR4, CD80, CIITA/SOCS1/CLEC16A, ICOSLG, ZMIZ1) with ETS1, RUNX3, THEMIS and TNFRSF14 playing key roles in thymic T cell selection. A further 13 regions had suggestive association evidence. In an expression quantitative trait meta-analysis of 1,469 whole blood samples, 20 of 38 (52.6%) tested loci had celiac risk variants correlated (P<0.0028, FDR 5%) with cis gene expression.\"\n", "!Series_summary\t\"\"\n", "!Series_summary\t\"*** Due to privacy concerns, the SNP data is not available with unrestricted access. Individuals wishing to obtain this data for research purposes may request access directly from the submitter (contact info below). ***\"\n", "!Series_overall_design\t\"Gene expression data was determined of untouched primary leucocytes (n=229) from unrelated Dutch and UK individuals.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['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": "557f4217", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "c01a5167", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:01:31.356551Z", "iopub.status.busy": "2025-03-25T08:01:31.356437Z", "iopub.status.idle": "2025-03-25T08:01:31.364215Z", "shell.execute_reply": "2025-03-25T08:01:31.363931Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Sample characteristics dictionary: {0: ['tissue: Peripheral blood']}\n" ] }, { "data": { "text/plain": [ "False" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import pandas as pd\n", "import os\n", "import json\n", "from typing import Optional, Callable, Dict, Any, List\n", "\n", "# 1. Gene Expression Data Availability\n", "# From the background information, we can see this is a gene expression dataset\n", "# that studied \"the effect of genetic variation on gene expression of untouched primary leucocytes\"\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# Looking at the sample characteristics dictionary\n", "print(\"Sample characteristics dictionary:\", {0: ['tissue: Peripheral blood']})\n", "\n", "# 2.1 Data Availability\n", "# The sample characteristics dictionary doesn't contain trait (celiac disease), age, or gender information\n", "trait_row = None # No information about celiac disease status\n", "age_row = None # No age information\n", "gender_row = None # No gender information\n", "\n", "# 2.2 Data Type Conversion\n", "# Even though we don't have data, we need to define these conversion functions\n", "\n", "def convert_trait(value):\n", " \"\"\"Convert trait value to binary (1 for celiac disease, 0 for control)\"\"\"\n", " if value is None:\n", " return None\n", " \n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip().lower()\n", " else:\n", " value = value.strip().lower()\n", " \n", " if 'celiac' in value or 'case' in value or 'patient' in value or 'cd' in value:\n", " return 1\n", " elif 'control' in value or 'healthy' in value or 'normal' in value:\n", " return 0\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age value to continuous (float)\"\"\"\n", " if value is None:\n", " return None\n", " \n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " else:\n", " value = value.strip()\n", " \n", " try:\n", " return float(value)\n", " except ValueError:\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", " if ':' in value:\n", " value = value.split(':', 1)[1].strip().lower()\n", " else:\n", " value = value.strip().lower()\n", " \n", " if value in ['female', 'f', 'woman']:\n", " return 0\n", " elif value in ['male', 'm', 'man']:\n", " return 1\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Check if trait data is available\n", "is_trait_available = trait_row is not None\n", "\n", "# Save cohort information\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", "# Skip this step since trait_row is None (clinical data not available)\n" ] }, { "cell_type": "markdown", "id": "06af0aa1", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "f09c47ac", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:01:31.365366Z", "iopub.status.busy": "2025-03-25T08:01:31.365257Z", "iopub.status.idle": "2025-03-25T08:01:31.858373Z", "shell.execute_reply": "2025-03-25T08:01:31.857970Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Matrix file found: ../../input/GEO/Celiac_Disease/GSE20332/GSE20332_series_matrix.txt.gz\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape: (22185, 229)\n", "First 20 gene/probe identifiers:\n", "Index(['ILMN_1343291', 'ILMN_1343292', 'ILMN_1343293', 'ILMN_1343294',\n", " 'ILMN_1651209', 'ILMN_1651217', 'ILMN_1651228', 'ILMN_1651229',\n", " 'ILMN_1651234', 'ILMN_1651235', 'ILMN_1651236', 'ILMN_1651237',\n", " 'ILMN_1651238', 'ILMN_1651254', 'ILMN_1651259', 'ILMN_1651260',\n", " 'ILMN_1651261', 'ILMN_1651262', 'ILMN_1651268', 'ILMN_1651278'],\n", " dtype='object', name='ID')\n" ] } ], "source": [ "# 1. Get the SOFT and matrix file paths again \n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "print(f\"Matrix file found: {matrix_file}\")\n", "\n", "# 2. Use the get_genetic_data function from the library to get the gene_data\n", "try:\n", " gene_data = get_genetic_data(matrix_file)\n", " print(f\"Gene data shape: {gene_data.shape}\")\n", " \n", " # 3. Print the first 20 row IDs (gene or probe identifiers)\n", " print(\"First 20 gene/probe identifiers:\")\n", " print(gene_data.index[:20])\n", "except Exception as e:\n", " print(f\"Error extracting gene data: {e}\")\n" ] }, { "cell_type": "markdown", "id": "bbadd0c9", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "7097bbaa", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:01:31.859826Z", "iopub.status.busy": "2025-03-25T08:01:31.859698Z", "iopub.status.idle": "2025-03-25T08:01:31.861829Z", "shell.execute_reply": "2025-03-25T08:01:31.861477Z" } }, "outputs": [], "source": [ "# These identifiers are Illumina probe IDs (ILMN_), not human gene symbols\n", "# They need to be mapped to standard gene symbols for meaningful analysis\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "99b294bd", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "d3873ed7", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:01:31.863060Z", "iopub.status.busy": "2025-03-25T08:01:31.862943Z", "iopub.status.idle": "2025-03-25T08:01:40.357905Z", "shell.execute_reply": "2025-03-25T08:01:40.357514Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene annotation preview:\n", "{'ID': ['ILMN_1698220', 'ILMN_1810835', 'ILMN_1782944', 'ILMN_1692858', 'ILMN_1668162'], 'Species': ['Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens'], 'Source': ['RefSeq', 'RefSeq', 'RefSeq', 'RefSeq', 'RefSeq'], 'Search_Key': ['ILMN_13666', 'ILMN_10478', 'ILMN_27850', 'ILMN_10309', 'ILMN_7652'], 'Transcript': ['ILMN_13666', 'ILMN_175835', 'ILMN_27850', 'ILMN_10309', 'ILMN_7652'], 'ILMN_Gene': ['PHTF2', 'SPRR3', 'GPR37L1', 'FBXO25', 'DGAT2L3'], 'Source_Reference_ID': ['NM_020432.2', 'NM_005416.1', 'NM_004767.2', 'NM_012173.3', 'NM_001013579.1'], 'RefSeq_ID': ['NM_020432.2', 'NM_005416.1', 'NM_004767.2', 'NM_012173.3', 'NM_001013579.1'], 'Entrez_Gene_ID': [57157.0, 6707.0, 9283.0, 26260.0, 158833.0], 'GI': [40254932.0, 4885606.0, 31377792.0, 34878756.0, 61888901.0], 'Accession': ['NM_020432.2', 'NM_005416.1', 'NM_004767.2', 'NM_012173.3', 'NM_001013579.1'], 'Symbol': ['PHTF2', 'SPRR3', 'GPR37L1', 'FBXO25', 'DGAT2L3'], 'Protein_Product': ['NP_065165.2', 'NP_005407.1', 'NP_004758.2', 'NP_036305.2', 'NP_001013597.1'], 'Array_Address_Id': [2900438.0, 2640692.0, 1690440.0, 1030747.0, 6480482.0], 'Probe_Type': ['S', 'S', 'S', 'A', 'S'], 'Probe_Start': [4677.0, 683.0, 2372.0, 1937.0, 782.0], 'SEQUENCE': ['CAAAGAGAATTGTGGCAGATGTTGTGTGTGAACTGTTGTTTCTTTGCCAC', 'GAAGCCAACCACCAGATGCTGGACACCCTCTTCCCATCTGTTTCTGTGTC', 'GATCCCTGGGTTGCCCTGTCCCAACCTCCTTGTTAGGTGCTTTCCCATAG', 'CTGGGGTTGGGGGCTGGTCTGTGCATAATCCTGGACTGTGATGGGAACAG', 'GTCAAGGCTCCACTGGGCTCCTGCCATACTCCAGGCCTATTGTCACTGTG'], 'Chromosome': ['7', '1', '1', '8', 'X'], 'Probe_Chr_Orientation': ['+', '+', '+', '+', '+'], 'Probe_Coordinates': ['77424374-77424423', '151242655-151242704', '200365170-200365219', '409448-409497', '69376459-69376508'], 'Definition': ['Homo sapiens putative homeodomain transcription factor 2 (PHTF2), mRNA.', 'Homo sapiens small proline-rich protein 3 (SPRR3), mRNA.', 'Homo sapiens G protein-coupled receptor 37 like 1 (GPR37L1), mRNA.', 'Homo sapiens F-box protein 25 (FBXO25), transcript variant 3, mRNA.', 'Homo sapiens diacylglycerol O-acyltransferase 2-like 3 (DGAT2L3), mRNA.'], 'Ontology_Component': ['endoplasmic reticulum [goid 5783] [pmid 11256614] [evidence IDA]', 'cornified envelope [goid 1533] [pmid 15232223] [evidence TAS]', 'membrane [goid 16020] [evidence IEA]; integral to membrane [goid 16021] [pmid 9539149] [evidence NAS]', 'ubiquitin ligase complex [goid 151] [pmid 10531035] [evidence NAS]', 'membrane [goid 16020] [evidence IEA]; integral to membrane [goid 16021] [evidence IEA]; endoplasmic reticulum [goid 5783] [evidence IEA]'], 'Ontology_Process': [nan, 'keratinocyte differentiation [goid 30216] [pmid 8325635] [evidence NAS]; wound healing [goid 42060] [pmid 10510474] [evidence TAS]; epidermis development [goid 8544] [pmid 8325635] [evidence NAS]; keratinization [goid 31424] [evidence IEA]', 'G-protein coupled receptor protein signaling pathway [goid 7186] [evidence IEA]; signal transduction [goid 7165] [evidence IEA]', 'protein ubiquitination [goid 16567] [pmid 10531035] [evidence NAS]', 'lipid biosynthesis [goid 8610] [evidence IEA]; lipid metabolism [goid 6629] [evidence IEA]'], 'Ontology_Function': [nan, 'structural molecule activity [goid 5198] [pmid 15232223] [evidence TAS]; protein binding [goid 5515] [pmid 10510474] [evidence IPI]', 'receptor activity [goid 4872] [evidence IEA]; G-protein coupled receptor activity, unknown ligand [goid 16526] [pmid 9539149] [evidence NAS]; rhodopsin-like receptor activity [goid 1584] [evidence IEA]', 'ubiquitin-protein ligase activity [goid 4842] [pmid 10531035] [evidence NAS]', 'acyltransferase activity [goid 8415] [evidence IEA]; transferase activity [goid 16740] [evidence IEA]'], 'Synonyms': ['DKFZP564F013; FLJ33324; MGC86999', nan, 'ET(B)R-LP-2; ETBR-LP-2', 'MGC51975; MGC20256; FBX25', 'AWAT1; DGA2'], 'GB_ACC': ['NM_020432.2', 'NM_005416.1', 'NM_004767.2', 'NM_012173.3', 'NM_001013579.1']}\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": "7e06160f", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "5cbd88b1", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:01:40.359311Z", "iopub.status.busy": "2025-03-25T08:01:40.359188Z", "iopub.status.idle": "2025-03-25T08:01:40.790184Z", "shell.execute_reply": "2025-03-25T08:01:40.789785Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene mapping data shape: (22185, 2)\n", "Sample of mapping data:\n", " ID Gene\n", "0 ILMN_1698220 PHTF2\n", "1 ILMN_1810835 SPRR3\n", "2 ILMN_1782944 GPR37L1\n", "3 ILMN_1692858 FBXO25\n", "4 ILMN_1668162 DGAT2L3\n", "Gene expression data shape after mapping: (17609, 229)\n", "First few gene symbols after mapping:\n", "Index(['A1BG', 'A2BP1', 'A2M', 'A2ML1', 'A4GALT', 'A4GNT', 'AAA1', 'AAAS',\n", " 'AACS', 'AADAC'],\n", " dtype='object', name='Gene')\n" ] } ], "source": [ "# 1. Identify which columns in the annotation data correspond to probe IDs and gene symbols\n", "# From the preview, we can see that the 'ID' column has the ILMN_ identifiers matching the gene expression data\n", "# The 'Symbol' column contains the gene symbols we need to map to\n", "\n", "# 2. Get a gene mapping dataframe using the get_gene_mapping function from the library\n", "prob_col = 'ID' # Column with probe identifiers (ILMN_*)\n", "gene_col = 'Symbol' # Column with gene symbols (e.g., PHTF2)\n", "\n", "mapping_data = get_gene_mapping(gene_annotation, prob_col, gene_col)\n", "print(f\"Gene mapping data shape: {mapping_data.shape}\")\n", "print(\"Sample of mapping data:\")\n", "print(mapping_data.head())\n", "\n", "# 3. Convert probe-level measurements to gene-level expression data using the mapping\n", "gene_data = apply_gene_mapping(gene_data, mapping_data)\n", "print(f\"Gene expression data shape after mapping: {gene_data.shape}\")\n", "print(\"First few gene symbols after mapping:\")\n", "print(gene_data.index[:10])\n" ] }, { "cell_type": "markdown", "id": "fa3ea7e7", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "fe4cd277", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:01:40.791651Z", "iopub.status.busy": "2025-03-25T08:01:40.791522Z", "iopub.status.idle": "2025-03-25T08:01:42.997913Z", "shell.execute_reply": "2025-03-25T08:01:42.997510Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data shape: (16991, 229)\n", "Sample of normalized gene data:\n", " GSM509318 GSM509319 GSM509320 GSM509321 GSM509322\n", "Gene \n", "A1BG -0.732172 -0.628766 -0.762766 -0.616788 -0.665529\n", "A2M -0.630958 -0.610310 -0.500944 -0.512666 -0.658750\n", "A2ML1 -0.573289 -0.490310 -0.516602 -0.550659 -0.517589\n", "A4GALT -0.543558 -0.544570 -0.338999 -0.565004 -0.530494\n", "A4GNT -0.504837 -0.519564 -0.538515 -0.609235 -0.551677\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data saved to ../../output/preprocess/Celiac_Disease/gene_data/GSE20332.csv\n", "Abnormality detected in the cohort: GSE20332. Preprocessing failed.\n", "Data is not usable for trait analysis because trait information is missing.\n" ] } ], "source": [ "# 1. Normalize gene symbols in the gene expression data\n", "gene_data_normalized = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"Normalized gene data shape: {gene_data_normalized.shape}\")\n", "print(\"Sample of normalized gene data:\")\n", "print(gene_data_normalized.iloc[:5, :5])\n", "\n", "# Save gene expression data\n", "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", "gene_data_normalized.to_csv(out_gene_data_file)\n", "print(f\"Gene expression data saved to {out_gene_data_file}\")\n", "\n", "# Since we determined in Step 2 that trait_row is None (no clinical data available),\n", "# we cannot perform data linking or further processing\n", "\n", "# Create an empty DataFrame to represent the lack of linked data\n", "linked_data = pd.DataFrame()\n", "\n", "# 5. Conduct quality check and save the cohort information\n", "# We already know is_trait_available is False since trait_row is None\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=False, # No trait data available\n", " is_biased=False, # Set to False instead of None for is_trait_available=False case\n", " df=linked_data,\n", " note=\"Dataset contains gene expression data but lacks phenotype information about Celiac Disease status\"\n", ")\n", "\n", "# 6. Since the data is not usable (no trait data), we do not save linked data\n", "print(\"Data is not usable for trait analysis because trait information is missing.\")" ] } ], "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 }