{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "d5ca9887", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:56:14.543561Z", "iopub.status.busy": "2025-03-25T07:56:14.543325Z", "iopub.status.idle": "2025-03-25T07:56:14.710037Z", "shell.execute_reply": "2025-03-25T07:56:14.709673Z" } }, "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 = \"Melanoma\"\n", "cohort = \"GSE148319\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Melanoma\"\n", "in_cohort_dir = \"../../input/GEO/Melanoma/GSE148319\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Melanoma/GSE148319.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Melanoma/gene_data/GSE148319.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Melanoma/clinical_data/GSE148319.csv\"\n", "json_path = \"../../output/preprocess/Melanoma/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "6ec0d8a8", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "782c5a09", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:56:14.711567Z", "iopub.status.busy": "2025-03-25T07:56:14.711409Z", "iopub.status.idle": "2025-03-25T07:56:14.976167Z", "shell.execute_reply": "2025-03-25T07:56:14.975794Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Files in the directory:\n", "['GSE148319_family.soft.gz', 'GSE148319_series_matrix.txt.gz']\n", "SOFT file: ../../input/GEO/Melanoma/GSE148319/GSE148319_family.soft.gz\n", "Matrix file: ../../input/GEO/Melanoma/GSE148319/GSE148319_series_matrix.txt.gz\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Dietary palmitic acid promotes a prometastatic epigenetic memory related to tumor innervation [IV]\"\n", "!Series_summary\t\"Metastasis is promoted by fatty acid (FA) uptake and metabolism1-2. How this works, or whether all dietary FAs are prometastatic, is not known. Here we show that dietary palmitic acid (PA), but not oleic acid (OA) or linoleic acid, promotes metastasis, indicating specificity of action for distinct FAs. Strikingly, tumours acutely exposed to a PA–rich diet remain highly metastatic even when serially transplanted. This PA–induced prometastatic memory requires the FA transporter CD36 as well as the epigenetically stable deposition of histone H3 lysine 4 trimethylation by the methyltransferase Set1A/COMPASS. Genes with this metastatic memory predominantly relate to a neural signature that stimulates intratumor oligodendrogenesis and perineural invasion, two parameters strongly correlated with metastasis but etiologically poorly understood3-4. Mechanistically, induction of the epigenetic neural signature and its associated long-term boost in metastasis downstream of PA require the transcription factor EGR2 and the oligodendrocyte-stimulating peptide galanin. We provide evidence for a long-term epigenetic stimulation of metastasis by a dietary metabolite related to tumor innervation. In addition to underscoring the potential danger of eating large amounts of PA (and perhaps other saturated fats), our results reveal novel epigenetic and neural-related therapeutic strategies for metastasis.\"\n", "!Series_overall_design\t\"3 biological replicates (2xVDH15 , 1xSCC25) with 3-4 techniclal replicates; FACS sorted CD36-bright and CD36-dim cells from non-targeting shRNA (PLKO) and short heirpin silenced CD36 (shCD36) orthotopic oral and melanoma tumor xenografts exposed to palmitic acid (PA)-rich, high-oleic acid (OA)-rich or control diet\"\n", "Sample Characteristics Dictionary:\n", "{0: ['sample id: 2254 2018', 'sample id: 2255 2018', 'sample id: 2257 2018', 'sample id: 2258 2018', 'sample id: 2259 2018', 'sample id: 2260 2018', 'sample id: 2261 2018', 'sample id: 2262 2018', 'sample id: 2263 2018', 'sample id: 2264 2018', 'sample id: 2265 2018', 'sample id: 2266 2018', 'sample id: 2267 2018', 'sample id: 2268 2018', 'sample id: 2269 2018', 'sample id: 2270 2018', 'sample id: 2271 2018', 'sample id: 2273 2018', 'sample id: 2274 2018', 'sample id: 2275 2018', 'sample id: 2276 2018', 'sample id: 2277 2018', 'sample id: 541 2019', 'sample id: 542 2019', 'sample id: 543 2019', 'sample id: 545 2019', 'sample id: 546 2019', 'sample id: 547 2019', 'sample id: 549 2019', 'sample id: 550 2019'], 1: ['hybridization batch: batch.1', 'hybridization batch: batch.3', 'hybridization batch: batch.5', 'hybridization batch: batch.4', 'hybridization batch: batch.2'], 2: ['scan batch: batch.4', 'scan batch: batch.6', 'scan batch: batch.5', 'scan batch: batch.7', 'scan batch: batch.2', 'scan batch: batch.1', 'scan batch: batch.3', 'scan batch: batch.8'], 3: ['biological replicate: hs.VDH15.1.biolrep.2', 'biological replicate: hs.VDH15.1.biolrep.1', 'biological replicate: hs.VDH15.1.biolrep.4', 'biological replicate: hs.VDH15.1.biolrep.3', 'biological replicate: hs.VDH15.1.biolrep.6', 'biological replicate: hs.VDH15.1.biolrep.5', 'biological replicate: hs.SCC25.1.biolrep.2', 'biological replicate: hs.SCC25.1.biolrep.1', 'biological replicate: hs.SCC25.1.biolrep.4', 'biological replicate: hs.SCC25.1.biolrep.3', 'biological replicate: hs.Melanoma.biolrep.1', 'biological replicate: hs.Melanoma.biolrep.3', 'biological replicate: hs.Melanoma.biolrep.2', 'biological replicate: hs.Melanoma.biolrep.4', 'biological replicate: hs.SCC25.2.biolrep.2', 'biological replicate: hs.SCC25.2.biolrep.1', 'biological replicate: hs.SCC25.2.biolrep.5', 'biological replicate: hs.SCC25.2.biolrep.3', 'biological replicate: hs.SCC25.2.biolrep.4', 'biological replicate: hs.VDH15.2.biolrep.3', 'biological replicate: hs.VDH15.2.biolrep.1', 'biological replicate: hs.VDH15.2.biolrep.6', 'biological replicate: hs.VDH15.2.biolrep.4', 'biological replicate: hs.VDH15.2.biolrep.2', 'biological replicate: hs.VDH15.2.biolrep.5'], 4: ['technical replicate: rep1', 'technical replicate: rep2', 'technical replicate: rep4', 'technical replicate: rep3'], 5: ['diet: control diet', 'diet: PA-rich diet', 'diet: OA-rich diet'], 6: ['cd36: CD36-bright', 'cd36: CD36-dim'], 7: ['shcd36: PLKO', 'shcd36: shCD36'], 8: ['cell line: VDH15 oral carcinoma cell line', 'cell line: SCC25 oral carcinoma cell line', 'cell line: melanoma cell line']}\n" ] } ], "source": [ "# 1. Check what files are actually in the directory\n", "import os\n", "print(\"Files in the directory:\")\n", "files = os.listdir(in_cohort_dir)\n", "print(files)\n", "\n", "# 2. Find appropriate files with more flexible pattern matching\n", "soft_file = None\n", "matrix_file = None\n", "\n", "for file in files:\n", " file_path = os.path.join(in_cohort_dir, file)\n", " # Look for files that might contain SOFT or matrix data with various possible extensions\n", " if 'soft' in file.lower() or 'family' in file.lower() or file.endswith('.soft.gz'):\n", " soft_file = file_path\n", " if 'matrix' in file.lower() or file.endswith('.txt.gz') or file.endswith('.tsv.gz'):\n", " matrix_file = file_path\n", "\n", "if not soft_file:\n", " print(\"Warning: Could not find a SOFT file. Using the first .gz file as fallback.\")\n", " gz_files = [f for f in files if f.endswith('.gz')]\n", " if gz_files:\n", " soft_file = os.path.join(in_cohort_dir, gz_files[0])\n", "\n", "if not matrix_file:\n", " print(\"Warning: Could not find a matrix file. Using the second .gz file as fallback if available.\")\n", " gz_files = [f for f in files if f.endswith('.gz')]\n", " if len(gz_files) > 1 and soft_file != os.path.join(in_cohort_dir, gz_files[1]):\n", " matrix_file = os.path.join(in_cohort_dir, gz_files[1])\n", " elif len(gz_files) == 1 and not soft_file:\n", " matrix_file = os.path.join(in_cohort_dir, gz_files[0])\n", "\n", "print(f\"SOFT file: {soft_file}\")\n", "print(f\"Matrix file: {matrix_file}\")\n", "\n", "# 3. Read files if found\n", "if soft_file and matrix_file:\n", " # 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", " \n", " try:\n", " background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n", " \n", " # Obtain the sample characteristics dictionary from the clinical dataframe\n", " sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n", " \n", " # 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", " except Exception as e:\n", " print(f\"Error processing files: {e}\")\n", " # Try swapping files if first attempt fails\n", " print(\"Trying to swap SOFT and matrix files...\")\n", " temp = soft_file\n", " soft_file = matrix_file\n", " matrix_file = temp\n", " try:\n", " background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n", " sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n", " print(\"Background Information:\")\n", " print(background_info)\n", " print(\"Sample Characteristics Dictionary:\")\n", " print(sample_characteristics_dict)\n", " except Exception as e:\n", " print(f\"Still error after swapping: {e}\")\n", "else:\n", " print(\"Could not find necessary files for processing.\")\n" ] }, { "cell_type": "markdown", "id": "228255a4", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "652969ca", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:56:14.977375Z", "iopub.status.busy": "2025-03-25T07:56:14.977260Z", "iopub.status.idle": "2025-03-25T07:56:15.004367Z", "shell.execute_reply": "2025-03-25T07:56:15.004084Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Preview of selected clinical features:\n", "{1: [0.0], 2: [0.0], 3: [0.0], 4: [0.0], 5: [0.0], 6: [0.0], 7: [0.0], 8: [0.0], 9: [0.0], 10: [0.0], 11: [0.0], 12: [0.0], 13: [0.0], 14: [0.0], 15: [0.0], 16: [0.0], 17: [0.0], 18: [0.0], 19: [0.0], 20: [0.0], 21: [0.0], 22: [0.0], 23: [0.0], 24: [0.0], 25: [0.0], 26: [0.0], 27: [0.0], 28: [0.0], 29: [0.0], 30: [0.0], 31: [0.0], 32: [0.0], 33: [0.0], 34: [0.0], 35: [1.0], 36: [1.0], 37: [1.0], 38: [1.0], 39: [1.0], 40: [1.0], 41: [1.0], 42: [1.0], 43: [1.0], 44: [1.0], 45: [1.0], 46: [1.0], 47: [1.0], 48: [1.0], 49: [1.0], 50: [1.0], 51: [0.0], 52: [0.0], 53: [0.0], 54: [0.0], 55: [0.0], 56: [0.0], 57: [0.0], 58: [0.0], 59: [0.0], 60: [0.0], 61: [0.0], 62: [0.0], 63: [0.0], 64: [0.0], 65: [0.0], 66: [0.0], 67: [0.0], 68: [0.0], 69: [0.0], 70: [0.0], 71: [0.0], 72: [0.0], 73: [0.0], 74: [0.0], 75: [0.0], 76: [0.0], 77: [0.0], 78: [0.0], 79: [0.0], 80: [0.0], 81: [0.0], 82: [0.0], 83: [0.0]}\n", "Clinical data saved to ../../output/preprocess/Melanoma/clinical_data/GSE148319.csv\n" ] } ], "source": [ "# 1. Gene Expression Data Availability\n", "# Based on the background information, this dataset appears to contain gene expression data from oral carcinoma and melanoma cell lines\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Identify rows for trait, age, and gender\n", "# Looking at sample characteristics dictionary, I can identify melanoma samples in row 3 (biological replicate)\n", "trait_row = 3\n", "# Age and gender information are not available in this dataset\n", "age_row = None\n", "gender_row = None\n", "\n", "# 2.2 Define conversion functions\n", "def convert_trait(value):\n", " \"\"\"\n", " Convert trait data to binary format (1 for Melanoma, 0 for non-Melanoma)\n", " \"\"\"\n", " if value is None:\n", " return None\n", " # Extract the value after the colon if present\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " # Check if the value contains \"Melanoma\"\n", " if \"Melanoma\" in value:\n", " return 1\n", " else:\n", " return 0\n", "\n", "def convert_age(value):\n", " \"\"\"\n", " Convert age data to continuous format\n", " Not used in this dataset as age data is not available\n", " \"\"\"\n", " if value is None:\n", " return None\n", " # Extract the value after the colon if present\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " try:\n", " return float(value)\n", " except (ValueError, TypeError):\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"\n", " Convert gender data to binary format (0 for female, 1 for male)\n", " Not used in this dataset as gender data is not available\n", " \"\"\"\n", " if value is None:\n", " return None\n", " # Extract the value after the colon if present\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip().lower()\n", " \n", " if value in [\"female\", \"f\"]:\n", " return 0\n", " elif value in [\"male\", \"m\"]:\n", " return 1\n", " else:\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Check if trait data is available (trait_row is not None)\n", "is_trait_available = trait_row is not None\n", "validate_and_save_cohort_info(\n", " is_final=False,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=is_gene_available,\n", " is_trait_available=is_trait_available\n", ")\n", "\n", "# 4. Clinical Feature Extraction\n", "# Check if clinical data is available (trait_row is not None)\n", "if trait_row is not None:\n", " # Use the sample characteristics dictionary to create a clinical dataframe\n", " # First, get the sample characteristics from the matrix file\n", " matrix_file = f\"{in_cohort_dir}/GSE148319_series_matrix.txt.gz\"\n", " \n", " # We'll extract the sample characteristics data from the matrix file\n", " sample_chars = {}\n", " with gzip.open(matrix_file, 'rt') as f:\n", " for line in f:\n", " if line.startswith('!Sample_characteristics_ch1'):\n", " parts = line.strip().split('\\t')\n", " for i, part in enumerate(parts[1:], 1):\n", " if i not in sample_chars:\n", " sample_chars[i] = []\n", " sample_chars[i].append(part.strip('\"'))\n", " # Stop reading once we reach the data section\n", " if line.startswith('!series_matrix_table_begin'):\n", " break\n", " \n", " # Convert to dataframe\n", " clinical_data = pd.DataFrame(sample_chars)\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 extracted clinical features\n", " preview = preview_df(selected_clinical_df)\n", " print(\"Preview of selected clinical features:\")\n", " print(preview)\n", " \n", " # Save the extracted clinical features\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\"Clinical data saved to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "9f20ecf4", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "4ca5f2f9", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:56:15.005515Z", "iopub.status.busy": "2025-03-25T07:56:15.005407Z", "iopub.status.idle": "2025-03-25T07:56:15.477006Z", "shell.execute_reply": "2025-03-25T07:56:15.476613Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "This appears to be a SuperSeries. Looking at the SOFT file to find potential subseries:\n", "No subseries references found in the first 1000 lines of the SOFT file.\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene data extraction result:\n", "Number of rows: 49372\n", "First 20 gene/probe identifiers:\n", "Index(['11715100_at', '11715101_s_at', '11715102_x_at', '11715103_x_at',\n", " '11715104_s_at', '11715105_at', '11715106_x_at', '11715107_s_at',\n", " '11715108_x_at', '11715109_at', '11715110_at', '11715111_s_at',\n", " '11715112_at', '11715113_x_at', '11715114_x_at', '11715115_s_at',\n", " '11715116_s_at', '11715117_x_at', '11715118_s_at', '11715119_s_at'],\n", " dtype='object', name='ID')\n" ] } ], "source": [ "# 1. First get the path to the soft and matrix files\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# 2. Looking more carefully at the background information\n", "# This is a SuperSeries which doesn't contain direct gene expression data\n", "# Need to investigate the soft file to find the subseries\n", "print(\"This appears to be a SuperSeries. Looking at the SOFT file to find potential subseries:\")\n", "\n", "# Open the SOFT file to try to identify subseries\n", "with gzip.open(soft_file, 'rt') as f:\n", " subseries_lines = []\n", " for i, line in enumerate(f):\n", " if 'Series_relation' in line and 'SuperSeries of' in line:\n", " subseries_lines.append(line.strip())\n", " if i > 1000: # Limit search to first 1000 lines\n", " break\n", "\n", "# Display the subseries found\n", "if subseries_lines:\n", " print(\"Found potential subseries references:\")\n", " for line in subseries_lines:\n", " print(line)\n", "else:\n", " print(\"No subseries references found in the first 1000 lines of the SOFT file.\")\n", "\n", "# Despite trying to extract gene data, we expect it might fail because this is a SuperSeries\n", "try:\n", " gene_data = get_genetic_data(matrix_file)\n", " print(\"\\nGene data extraction result:\")\n", " print(\"Number of rows:\", len(gene_data))\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", " print(\"This confirms the dataset is a SuperSeries without direct gene expression data.\")\n" ] }, { "cell_type": "markdown", "id": "87f83174", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "bf19cc02", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:56:15.478322Z", "iopub.status.busy": "2025-03-25T07:56:15.478194Z", "iopub.status.idle": "2025-03-25T07:56:15.480114Z", "shell.execute_reply": "2025-03-25T07:56:15.479806Z" } }, "outputs": [], "source": [ "# Looking at the gene identifiers, these appear to be Affymetrix probe IDs (format like \"11715100_at\")\n", "# rather than standard human gene symbols (like BRCA1, TP53, etc.)\n", "# These probe IDs need to be mapped to standard gene symbols for proper analysis\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "c5c26e80", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "d0fd4e95", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:56:15.481198Z", "iopub.status.busy": "2025-03-25T07:56:15.481088Z", "iopub.status.idle": "2025-03-25T07:56:27.923217Z", "shell.execute_reply": "2025-03-25T07:56:27.922519Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene annotation preview:\n", "{'ID': ['11715100_at', '11715101_s_at', '11715102_x_at', '11715103_x_at', '11715104_s_at'], 'GeneChip Array': ['Human Genome PrimeView Array', 'Human Genome PrimeView Array', 'Human Genome PrimeView Array', 'Human Genome PrimeView Array', 'Human Genome PrimeView Array'], 'Species Scientific Name': ['Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens'], 'Annotation Date': ['30-Mar-16', '30-Mar-16', '30-Mar-16', '30-Mar-16', '30-Mar-16'], 'Sequence Type': ['Consensus sequence', 'Consensus sequence', 'Consensus sequence', 'Consensus sequence', 'Consensus sequence'], 'Sequence Source': ['Affymetrix Proprietary Database', 'Affymetrix Proprietary Database', 'Affymetrix Proprietary Database', 'Affymetrix Proprietary Database', 'Affymetrix Proprietary Database'], 'Transcript ID(Array Design)': ['g21264570', 'g21264570', 'g21264570', 'g22748780', 'g30039713'], 'Target Description': ['g21264570 /TID=g21264570 /CNT=1 /FEA=FLmRNA /TIER=FL /STK=0 /DEF=g21264570 /REP_ORG=Homo sapiens', 'g21264570 /TID=g21264570 /CNT=1 /FEA=FLmRNA /TIER=FL /STK=0 /DEF=g21264570 /REP_ORG=Homo sapiens', 'g21264570 /TID=g21264570 /CNT=1 /FEA=FLmRNA /TIER=FL /STK=0 /DEF=g21264570 /REP_ORG=Homo sapiens', 'g22748780 /TID=g22748780 /CNT=1 /FEA=FLmRNA /TIER=FL /STK=0 /DEF=g22748780 /REP_ORG=Homo sapiens', 'g30039713 /TID=g30039713 /CNT=1 /FEA=FLmRNA /TIER=FL /STK=0 /DEF=g30039713 /REP_ORG=Homo sapiens'], 'GB_ACC': [nan, nan, nan, nan, nan], 'GI': [21264570.0, 21264570.0, 21264570.0, 22748780.0, 30039713.0], 'Representative Public ID': ['g21264570', 'g21264570', 'g21264570', 'g22748780', 'g30039713'], 'Archival UniGene Cluster': ['---', '---', '---', '---', '---'], 'UniGene ID': ['Hs.247813', 'Hs.247813', 'Hs.247813', 'Hs.465643', 'Hs.352515'], 'Genome Version': ['February 2009 (Genome Reference Consortium GRCh37)', 'February 2009 (Genome Reference Consortium GRCh37)', 'February 2009 (Genome Reference Consortium GRCh37)', 'February 2009 (Genome Reference Consortium GRCh37)', 'February 2009 (Genome Reference Consortium GRCh37)'], 'Alignments': ['chr6:26271145-26271612 (-) // 100.0 // p22.2', 'chr6:26271145-26271612 (-) // 100.0 // p22.2', 'chr6:26271145-26271612 (-) // 100.0 // p22.2', 'chr19:4639529-5145579 (+) // 48.53 // p13.3', 'chr17:72920369-72929640 (+) // 100.0 // q25.1'], 'Gene Title': ['histone cluster 1, H3g', 'histone cluster 1, H3g', 'histone cluster 1, H3g', 'tumor necrosis factor, alpha-induced protein 8-like 1', 'otopetrin 2'], 'Gene Symbol': ['HIST1H3G', 'HIST1H3G', 'HIST1H3G', 'TNFAIP8L1', 'OTOP2'], 'Chromosomal Location': ['chr6p22.2', 'chr6p22.2', 'chr6p22.2', 'chr19p13.3', 'chr17q25.1'], 'Unigene Cluster Type': ['full length', 'full length', 'full length', 'full length', 'full length'], 'Ensembl': ['ENSG00000273983 /// OTTHUMG00000014436', 'ENSG00000273983 /// OTTHUMG00000014436', 'ENSG00000273983 /// OTTHUMG00000014436', 'ENSG00000185361 /// OTTHUMG00000182013', 'ENSG00000183034 /// OTTHUMG00000179215'], 'Entrez Gene': ['8355', '8355', '8355', '126282', '92736'], 'SwissProt': ['P68431', 'P68431', 'P68431', 'Q8WVP5', 'Q7RTS6'], 'EC': ['---', '---', '---', '---', '---'], 'OMIM': ['602815', '602815', '602815', '615869', '607827'], 'RefSeq Protein ID': ['NP_003525', 'NP_003525', 'NP_003525', 'NP_001161414 /// NP_689575 /// XP_005259544 /// XP_011525982', 'NP_835454 /// XP_011523781'], 'RefSeq Transcript ID': ['NM_003534', 'NM_003534', 'NM_003534', 'NM_001167942 /// NM_152362 /// XM_005259487 /// XM_011527680', 'NM_178160 /// XM_011525479'], 'Gene Ontology Biological Process': ['0000183 // chromatin silencing at rDNA // traceable author statement /// 0002230 // positive regulation of defense response to virus by host // inferred from mutant phenotype /// 0006325 // chromatin organization // traceable author statement /// 0006334 // nucleosome assembly // inferred from direct assay /// 0006334 // nucleosome assembly // inferred from mutant phenotype /// 0006335 // DNA replication-dependent nucleosome assembly // inferred from direct assay /// 0007264 // small GTPase mediated signal transduction // traceable author statement /// 0007596 // blood coagulation // traceable author statement /// 0010467 // gene expression // traceable author statement /// 0031047 // gene silencing by RNA // traceable author statement /// 0032776 // DNA methylation on cytosine // traceable author statement /// 0040029 // regulation of gene expression, epigenetic // traceable author statement /// 0044267 // cellular protein metabolic process // traceable author statement /// 0045814 // negative regulation of gene expression, epigenetic // traceable author statement /// 0051290 // protein heterotetramerization // inferred from direct assay /// 0060968 // regulation of gene silencing // inferred from direct assay /// 0098792 // xenophagy // inferred from mutant phenotype', '0000183 // chromatin silencing at rDNA // traceable author statement /// 0002230 // positive regulation of defense response to virus by host // inferred from mutant phenotype /// 0006325 // chromatin organization // traceable author statement /// 0006334 // nucleosome assembly // inferred from direct assay /// 0006334 // nucleosome assembly // inferred from mutant phenotype /// 0006335 // DNA replication-dependent nucleosome assembly // inferred from direct assay /// 0007264 // small GTPase mediated signal transduction // traceable author statement /// 0007596 // blood coagulation // traceable author statement /// 0010467 // gene expression // traceable author statement /// 0031047 // gene silencing by RNA // traceable author statement /// 0032776 // DNA methylation on cytosine // traceable author statement /// 0040029 // regulation of gene expression, epigenetic // traceable author statement /// 0044267 // cellular protein metabolic process // traceable author statement /// 0045814 // negative regulation of gene expression, epigenetic // traceable author statement /// 0051290 // protein heterotetramerization // inferred from direct assay /// 0060968 // regulation of gene silencing // inferred from direct assay /// 0098792 // xenophagy // inferred from mutant phenotype', '0000183 // chromatin silencing at rDNA // traceable author statement /// 0002230 // positive regulation of defense response to virus by host // inferred from mutant phenotype /// 0006325 // chromatin organization // traceable author statement /// 0006334 // nucleosome assembly // inferred from direct assay /// 0006334 // nucleosome assembly // inferred from mutant phenotype /// 0006335 // DNA replication-dependent nucleosome assembly // inferred from direct assay /// 0007264 // small GTPase mediated signal transduction // traceable author statement /// 0007596 // blood coagulation // traceable author statement /// 0010467 // gene expression // traceable author statement /// 0031047 // gene silencing by RNA // traceable author statement /// 0032776 // DNA methylation on cytosine // traceable author statement /// 0040029 // regulation of gene expression, epigenetic // traceable author statement /// 0044267 // cellular protein metabolic process // traceable author statement /// 0045814 // negative regulation of gene expression, epigenetic // traceable author statement /// 0051290 // protein heterotetramerization // inferred from direct assay /// 0060968 // regulation of gene silencing // inferred from direct assay /// 0098792 // xenophagy // inferred from mutant phenotype', '0032007 // negative regulation of TOR signaling // not recorded /// 0032007 // negative regulation of TOR signaling // inferred from sequence or structural similarity', '---'], 'Gene Ontology Cellular Component': ['0000228 // nuclear chromosome // inferred from direct assay /// 0000786 // nucleosome // inferred from direct assay /// 0000788 // nuclear nucleosome // inferred from direct assay /// 0005576 // extracellular region // traceable author statement /// 0005634 // nucleus // inferred from direct assay /// 0005654 // nucleoplasm // traceable author statement /// 0005694 // chromosome // inferred from electronic annotation /// 0016020 // membrane // inferred from direct assay /// 0043234 // protein complex // inferred from direct assay /// 0070062 // extracellular exosome // inferred from direct assay', '0000228 // nuclear chromosome // inferred from direct assay /// 0000786 // nucleosome // inferred from direct assay /// 0000788 // nuclear nucleosome // inferred from direct assay /// 0005576 // extracellular region // traceable author statement /// 0005634 // nucleus // inferred from direct assay /// 0005654 // nucleoplasm // traceable author statement /// 0005694 // chromosome // inferred from electronic annotation /// 0016020 // membrane // inferred from direct assay /// 0043234 // protein complex // inferred from direct assay /// 0070062 // extracellular exosome // inferred from direct assay', '0000228 // nuclear chromosome // inferred from direct assay /// 0000786 // nucleosome // inferred from direct assay /// 0000788 // nuclear nucleosome // inferred from direct assay /// 0005576 // extracellular region // traceable author statement /// 0005634 // nucleus // inferred from direct assay /// 0005654 // nucleoplasm // traceable author statement /// 0005694 // chromosome // inferred from electronic annotation /// 0016020 // membrane // inferred from direct assay /// 0043234 // protein complex // inferred from direct assay /// 0070062 // extracellular exosome // inferred from direct assay', '0005737 // cytoplasm // not recorded /// 0005737 // cytoplasm // inferred from sequence or structural similarity', '0016020 // membrane // inferred from electronic annotation /// 0016021 // integral component of membrane // inferred from electronic annotation'], 'Gene Ontology Molecular Function': ['0003677 // DNA binding // inferred from electronic annotation /// 0005515 // protein binding // inferred from physical interaction /// 0042393 // histone binding // inferred from physical interaction /// 0046982 // protein heterodimerization activity // inferred from electronic annotation', '0003677 // DNA binding // inferred from electronic annotation /// 0005515 // protein binding // inferred from physical interaction /// 0042393 // histone binding // inferred from physical interaction /// 0046982 // protein heterodimerization activity // inferred from electronic annotation', '0003677 // DNA binding // inferred from electronic annotation /// 0005515 // protein binding // inferred from physical interaction /// 0042393 // histone binding // inferred from physical interaction /// 0046982 // protein heterodimerization activity // inferred from electronic annotation', '0005515 // protein binding // inferred from physical interaction', '---'], 'Pathway': ['---', '---', '---', '---', '---'], 'InterPro': ['IPR007125 // Histone H2A/H2B/H3 // 9.3E-34 /// IPR007125 // Histone H2A/H2B/H3 // 1.7E-37', 'IPR007125 // Histone H2A/H2B/H3 // 9.3E-34 /// IPR007125 // Histone H2A/H2B/H3 // 1.7E-37', 'IPR007125 // Histone H2A/H2B/H3 // 9.3E-34 /// IPR007125 // Histone H2A/H2B/H3 // 1.7E-37', 'IPR008477 // Protein of unknown function DUF758 // 8.4E-86 /// IPR008477 // Protein of unknown function DUF758 // 6.8E-90', 'IPR004878 // Otopetrin // 9.4E-43 /// IPR004878 // Otopetrin // 9.4E-43 /// IPR004878 // Otopetrin // 9.4E-43 /// IPR004878 // Otopetrin // 3.9E-18 /// IPR004878 // Otopetrin // 3.8E-20 /// IPR004878 // Otopetrin // 5.2E-16'], 'Annotation Description': ['This probe set was annotated using the Matching Probes based pipeline to a Entrez Gene identifier using 4 transcripts. // false // Matching Probes // A', 'This probe set was annotated using the Matching Probes based pipeline to a Entrez Gene identifier using 4 transcripts. // false // Matching Probes // A', 'This probe set was annotated using the Matching Probes based pipeline to a Entrez Gene identifier using 4 transcripts. // false // Matching Probes // A', 'This probe set was annotated using the Matching Probes based pipeline to a Entrez Gene identifier using 9 transcripts. // false // Matching Probes // A', 'This probe set was annotated using the Matching Probes based pipeline to a Entrez Gene identifier using 6 transcripts. // false // Matching Probes // A'], 'Annotation Transcript Cluster': ['ENST00000614378(11),NM_003534(11),OTTHUMT00000040099(11),uc003nhi.3', 'ENST00000614378(11),NM_003534(11),OTTHUMT00000040099(11),uc003nhi.3', 'ENST00000614378(11),NM_003534(11),OTTHUMT00000040099(11),uc003nhi.3', 'BC017672(11),BC044250(9),ENST00000327473(11),ENST00000536716(11),NM_001167942(11),NM_152362(11),OTTHUMT00000458662(11),uc002max.3,uc021une.1', 'ENST00000331427(11),ENST00000580223(11),NM_178160(11),OTTHUMT00000445306(11),uc010wrp.2,XM_011525479(11)'], 'Transcript Assignments': ['ENST00000614378 // ensembl_havana_transcript:known chromosome:GRCh38:6:26269405:26271815:-1 gene:ENSG00000273983 gene_biotype:protein_coding transcript_biotype:protein_coding // ensembl // 11 // --- /// NM_003534 // Homo sapiens histone cluster 1, H3g (HIST1H3G), mRNA. // refseq // 11 // --- /// OTTHUMT00000040099 // otter:known chromosome:VEGA61:6:26269405:26271815:-1 gene:OTTHUMG00000014436 gene_biotype:protein_coding transcript_biotype:protein_coding // vega // 11 // --- /// uc003nhi.3 // --- // ucsc_genes // 11 // ---', 'ENST00000614378 // ensembl_havana_transcript:known chromosome:GRCh38:6:26269405:26271815:-1 gene:ENSG00000273983 gene_biotype:protein_coding transcript_biotype:protein_coding // ensembl // 11 // --- /// GENSCAN00000029819 // cdna:genscan chromosome:GRCh38:6:26270974:26271384:-1 transcript_biotype:protein_coding // ensembl // 11 // --- /// NM_003534 // Homo sapiens histone cluster 1, H3g (HIST1H3G), mRNA. // refseq // 11 // --- /// OTTHUMT00000040099 // otter:known chromosome:VEGA61:6:26269405:26271815:-1 gene:OTTHUMG00000014436 gene_biotype:protein_coding transcript_biotype:protein_coding // vega // 11 // --- /// uc003nhi.3 // --- // ucsc_genes // 11 // ---', 'ENST00000614378 // ensembl_havana_transcript:known chromosome:GRCh38:6:26269405:26271815:-1 gene:ENSG00000273983 gene_biotype:protein_coding transcript_biotype:protein_coding // ensembl // 11 // --- /// NM_003534 // Homo sapiens histone cluster 1, H3g (HIST1H3G), mRNA. // refseq // 11 // --- /// OTTHUMT00000040099 // otter:known chromosome:VEGA61:6:26269405:26271815:-1 gene:OTTHUMG00000014436 gene_biotype:protein_coding transcript_biotype:protein_coding // vega // 11 // --- /// uc003nhi.3 // --- // ucsc_genes // 11 // ---', 'BC017672 // Homo sapiens tumor necrosis factor, alpha-induced protein 8-like 1, mRNA (cDNA clone MGC:17791 IMAGE:3885999), complete cds. // gb // 11 // --- /// BC044250 // accn=BC044250 class=mRNAlike lncRNA name=Human lncRNA ref=JounralRNA transcriptId=673 cpcScore=-0.1526100 cnci=-0.1238602 // noncode // 9 // --- /// BC044250 // Homo sapiens tumor necrosis factor, alpha-induced protein 8-like 1, mRNA (cDNA clone IMAGE:5784807). // gb // 9 // --- /// ENST00000327473 // ensembl_havana_transcript:known chromosome:GRCh38:19:4639518:4655568:1 gene:ENSG00000185361 gene_biotype:protein_coding transcript_biotype:protein_coding // ensembl // 11 // --- /// ENST00000536716 // ensembl:known chromosome:GRCh38:19:4640017:4655568:1 gene:ENSG00000185361 gene_biotype:protein_coding transcript_biotype:protein_coding // ensembl // 11 // --- /// NM_001167942 // Homo sapiens tumor necrosis factor, alpha-induced protein 8-like 1 (TNFAIP8L1), transcript variant 1, mRNA. // refseq // 11 // --- /// NM_152362 // Homo sapiens tumor necrosis factor, alpha-induced protein 8-like 1 (TNFAIP8L1), transcript variant 2, mRNA. // refseq // 11 // --- /// NONHSAT060631 // Non-coding transcript identified by NONCODE: Exonic // noncode // 9 // --- /// OTTHUMT00000458662 // otter:known chromosome:VEGA61:19:4639518:4655568:1 gene:OTTHUMG00000182013 gene_biotype:protein_coding transcript_biotype:protein_coding // vega // 11 // --- /// uc002max.3 // --- // ucsc_genes // 11 // --- /// uc021une.1 // --- // ucsc_genes // 11 // ---', 'ENST00000331427 // ensembl:known chromosome:GRCh38:17:74924275:74933911:1 gene:ENSG00000183034 gene_biotype:protein_coding transcript_biotype:protein_coding // ensembl // 11 // --- /// ENST00000580223 // havana:known chromosome:GRCh38:17:74924603:74933912:1 gene:ENSG00000183034 gene_biotype:protein_coding transcript_biotype:protein_coding // ensembl // 11 // --- /// GENSCAN00000013715 // cdna:genscan chromosome:GRCh38:17:74924633:74933545:1 transcript_biotype:protein_coding // ensembl // 11 // --- /// NM_178160 // Homo sapiens otopetrin 2 (OTOP2), mRNA. // refseq // 11 // --- /// OTTHUMT00000445306 // otter:known chromosome:VEGA61:17:74924603:74933912:1 gene:OTTHUMG00000179215 gene_biotype:protein_coding transcript_biotype:protein_coding // vega // 11 // --- /// uc010wrp.2 // --- // ucsc_genes // 11 // --- /// XM_011525479 // PREDICTED: Homo sapiens otopetrin 2 (OTOP2), transcript variant X1, mRNA. // refseq // 11 // ---'], 'Annotation Notes': ['---', '---', 'GENSCAN00000029819 // ensembl // 4 // Cross Hyb Matching Probes', '---', '---'], 'SPOT_ID': [nan, nan, nan, nan, nan]}\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": "88152ce3", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "7b1819db", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:56:27.925177Z", "iopub.status.busy": "2025-03-25T07:56:27.925049Z", "iopub.status.idle": "2025-03-25T07:56:28.695033Z", "shell.execute_reply": "2025-03-25T07:56:28.694388Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Converted from 49372 probes to 19963 genes\n", "First 10 gene symbols:\n", "Index(['A1BG', 'A1CF', 'A2M', 'A2ML1', 'A3GALT2', 'A4GALT', 'A4GNT', 'AAAS',\n", " 'AACS', 'AACSP1'],\n", " dtype='object', name='Gene')\n" ] } ], "source": [ "# 1. Identify the columns in gene_annotation that correspond to probe IDs and gene symbols\n", "probe_id_col = 'ID'\n", "gene_symbol_col = 'Gene Symbol'\n", "\n", "# 2. Extract the mapping dataframe containing probe IDs and gene symbols\n", "gene_mapping = get_gene_mapping(gene_annotation, probe_id_col, gene_symbol_col)\n", "\n", "# 3. Load the gene expression data\n", "genetic_data = get_genetic_data(matrix_file)\n", "\n", "# 4. Apply the gene mapping to convert probe-level measurements to gene-level expression\n", "gene_data = apply_gene_mapping(genetic_data, gene_mapping)\n", "\n", "# Print information about the resulting gene data\n", "print(f\"Converted from {len(genetic_data)} probes to {len(gene_data)} genes\")\n", "print(\"First 10 gene symbols:\")\n", "print(gene_data.index[:10])\n" ] }, { "cell_type": "markdown", "id": "7a52d359", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "b71f3ac2", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:56:28.696986Z", "iopub.status.busy": "2025-03-25T07:56:28.696830Z", "iopub.status.idle": "2025-03-25T07:56:37.277712Z", "shell.execute_reply": "2025-03-25T07:56:37.277182Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Top 10 gene indices before normalization: ['A1BG', 'A1CF', 'A2M', 'A2ML1', 'A3GALT2', 'A4GALT', 'A4GNT', 'AAAS', 'AACS', 'AACSP1']\n", "Top 10 gene indices after normalization: ['A1BG', 'A1CF', 'A2M', 'A2ML1', 'A3GALT2', 'A4GALT', 'A4GNT', 'AAAS', 'AACS', 'AACSP1']\n", "Shape of normalized gene data: (19758, 83)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Saved normalized gene data to ../../output/preprocess/Melanoma/gene_data/GSE148319.csv\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Saved clinical data to ../../output/preprocess/Melanoma/clinical_data/GSE148319.csv\n", "Shape of linked data: (83, 19759)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Shape of linked data after handling missing values: (83, 19759)\n", "Quartiles for 'Melanoma':\n", " 25%: 0.0\n", " 50% (Median): 0.0\n", " 75%: 0.0\n", "Min: 0.0\n", "Max: 0.0\n", "The distribution of the feature 'Melanoma' in this dataset is severely biased.\n", "\n", "Dataset validation failed. Final linked data not saved.\n" ] } ], "source": [ "# 1. Normalize gene symbols in the gene expression data\n", "print(f\"Top 10 gene indices before normalization: {gene_data.index[:10].tolist()}\")\n", "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"Top 10 gene indices after normalization: {normalized_gene_data.index[:10].tolist()}\")\n", "print(f\"Shape of normalized gene data: {normalized_gene_data.shape}\")\n", "\n", "# Create directory for gene data file if it doesn't exist\n", "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", "# Save the normalized gene data\n", "normalized_gene_data.to_csv(out_gene_data_file)\n", "print(f\"Saved normalized gene data to {out_gene_data_file}\")\n", "\n", "# 2. Extract clinical features using the clinical data from step 1\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", "# Extract clinical features using the convert_trait function from step 2\n", "selected_clinical_df = geo_select_clinical_features(\n", " clinical_df=clinical_data,\n", " trait=trait,\n", " trait_row=1, # From step 2\n", " convert_trait=convert_trait,\n", " age_row=None,\n", " convert_age=None,\n", " gender_row=None,\n", " convert_gender=None\n", ")\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)\n", "print(f\"Saved clinical data to {out_clinical_data_file}\")\n", "\n", "# 3. Link clinical and genetic data\n", "linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)\n", "print(f\"Shape of linked data: {linked_data.shape}\")\n", "\n", "# 4. Handle missing values in the linked data\n", "linked_data = handle_missing_values(linked_data, trait)\n", "print(f\"Shape of linked data after handling missing values: {linked_data.shape}\")\n", "\n", "# 5. Determine if the trait and demographic features are biased\n", "is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)\n", "\n", "# 6. Validate the dataset and save 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 juvenile myositis (JM) and childhood-onset lupus (cSLE) skin biopsies.\"\n", ")\n", "\n", "# 7. Save the linked data if it's usable\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\"Saved processed linked data to {out_data_file}\")\n", "else:\n", " print(\"Dataset validation failed. Final linked data 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 }