{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "ccf93b63", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:04:03.306129Z", "iopub.status.busy": "2025-03-25T06:04:03.305913Z", "iopub.status.idle": "2025-03-25T06:04:03.471924Z", "shell.execute_reply": "2025-03-25T06:04:03.471532Z" } }, "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 = \"Ovarian_Cancer\"\n", "cohort = \"GSE146964\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Ovarian_Cancer\"\n", "in_cohort_dir = \"../../input/GEO/Ovarian_Cancer/GSE146964\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Ovarian_Cancer/GSE146964.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Ovarian_Cancer/gene_data/GSE146964.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Ovarian_Cancer/clinical_data/GSE146964.csv\"\n", "json_path = \"../../output/preprocess/Ovarian_Cancer/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "ccf4f9c1", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "e51e4c09", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:04:03.473446Z", "iopub.status.busy": "2025-03-25T06:04:03.473293Z", "iopub.status.idle": "2025-03-25T06:04:03.815940Z", "shell.execute_reply": "2025-03-25T06:04:03.815594Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Files in the directory:\n", "['GSE146964_family.soft.gz', 'GSE146964_series_matrix.txt.gz']\n", "SOFT file: ../../input/GEO/Ovarian_Cancer/GSE146964/GSE146964_family.soft.gz\n", "Matrix file: ../../input/GEO/Ovarian_Cancer/GSE146964/GSE146964_series_matrix.txt.gz\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Unraveling Tumor-Immune Heterogeneity in Advanced Ovarian Cancer Uncovers Immunogenic Effect of Chemotherapy [naïve]\"\n", "!Series_summary\t\"In metastatic cancer, the degree of heterogeneity of the tumor-immune microenvironment and its molecular underpinnings remain largely unstudied. To characterize the tumor-immune interface at baseline and during neoadjuvant chemotherapy in high-grade serous ovarian cancer (HGSOC), we performed immunogenomics analysis of treatment-naive and paired pre/post-chemotherapy treated samples. In treatment-naive HGSOC, we find that immune cell-excluded and inflammatory microenvironments co-exist within the same individuals and within the same tumor sites, indicating ubiquitous variability in immune cell infiltration. Analysis of tumor microenvironment cell composition, DNA copy number, mutations and gene expression showed that immune cell exclusion was associated with amplification of Myc target genes and increased expression of canonical Wnt signaling in treatment-naive HGSOC. Following neoadjuvant chemotherapy, increased natural killer cell infiltration and oligoclonal expansion of T cells were detected. We demonstrate that the tumor-immune microenvironment of advanced HGSOC is intrinsically heterogeneous and that chemotherapy induces local immune activation, suggesting that chemotherapy can potentiate the immunogenicity of immune-excluded HGSOC tumors.\"\n", "!Series_summary\t\"The goal of this particular experiment was quantify RNA expression using microarray technology, and then evaluate differences in the trasncirptomic landscape of treatment naïve metastatic high grade serous ovarian cancer.\"\n", "!Series_overall_design\t\"Samples analyzed: Described in figure 1a. Ten patients with 38 Affymetrix mRNA microarrays (I.e Multiple samples per patient).\"\n", "Sample Characteristics Dictionary:\n", "{0: ['subject id: 10', 'subject id: 06', 'subject id: 01', 'subject id: 04', 'subject id: 05', 'subject id: 13', 'subject id: 16', 'subject id: 17'], 1: ['gender: Female'], 2: ['tissue: Omentum', 'tissue: Paracolic gutter', 'tissue: Ovary', 'tissue: Adnexal surface', 'tissue: Pouch of Douglas', 'tissue: Right psoas', 'tissue: Serosa'], 3: ['condition: Malignant'], 4: ['tumor type: High grade serous ovarian cancer'], 5: ['tumor stage: IIIC', 'tumor stage: IV', 'tumor stage: IVB'], 6: ['sample type: FFPE']}\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": "f1b39d93", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "9434237f", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:04:03.817189Z", "iopub.status.busy": "2025-03-25T06:04:03.817066Z", "iopub.status.idle": "2025-03-25T06:04:03.824451Z", "shell.execute_reply": "2025-03-25T06:04:03.824123Z" } }, "outputs": [ { "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\n", "\n", "# Based on the previously provided Sample Characteristics Dictionary:\n", "# {0: ['subject id: 10', 'subject id: 06', 'subject id: 01', 'subject id: 04', 'subject id: 05', 'subject id: 13', 'subject id: 16', 'subject id: 17'], \n", "# 1: ['gender: Female'], \n", "# 2: ['tissue: Omentum', 'tissue: Paracolic gutter', 'tissue: Ovary', 'tissue: Adnexal surface', 'tissue: Pouch of Douglas', 'tissue: Right psoas', 'tissue: Serosa'], \n", "# 3: ['condition: Malignant'], \n", "# 4: ['tumor type: High grade serous ovarian cancer'], \n", "# 5: ['tumor stage: IIIC', 'tumor stage: IV', 'tumor stage: IVB'], \n", "# 6: ['sample type: FFPE']}\n", "\n", "# 1. Gene Expression Data Availability\n", "# Based on the background information, this dataset contains mRNA microarrays,\n", "# which indicates gene expression data is available\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "\n", "# For trait (Ovarian Cancer): \n", "# Looking at the sample characteristics dictionary, all samples have \"condition: Malignant\"\n", "# and \"tumor type: High grade serous ovarian cancer\" (rows 3 and 4)\n", "# Since all samples are cancer cases with no controls for comparison, \n", "# there's no variability in the trait value, making it unusable for associative studies\n", "trait_row = None\n", "\n", "# For age:\n", "# There is no age information in the sample characteristics dictionary\n", "age_row = None\n", "\n", "# For gender:\n", "# All samples are from females (row 1)\n", "# Since there's only one value (all female), there's no variability in gender\n", "gender_row = None\n", "\n", "# 2.2 Data Type Conversion Functions\n", "\n", "# Define conversion functions (even though we won't use them due to data unavailability)\n", "def convert_trait(value):\n", " if pd.isna(value) or value is None:\n", " return None\n", " if isinstance(value, str) and ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " if 'malignant' in value.lower() or 'cancer' in value.lower():\n", " return 1\n", " elif 'normal' in value.lower() or 'healthy' in value.lower() or 'benign' in value.lower():\n", " return 0\n", " return None\n", "\n", "def convert_age(value):\n", " if pd.isna(value) or value is None:\n", " return None\n", " if isinstance(value, str) and ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " try:\n", " return float(value)\n", " except:\n", " return None\n", "\n", "def convert_gender(value):\n", " if pd.isna(value) or value is None:\n", " return None\n", " if isinstance(value, str) and ':' in value:\n", " value = value.split(':', 1)[1].strip().lower()\n", " \n", " if 'female' in value:\n", " return 0\n", " elif 'male' in value:\n", " return 1\n", " return None\n", "\n", "# 3. Save Metadata\n", "is_trait_available = trait_row is not None\n", "\n", "# Validate and save cohort info\n", "validate_and_save_cohort_info(\n", " is_final=False,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=is_gene_available,\n", " is_trait_available=is_trait_available\n", ")\n", "\n", "# 4. Clinical Feature Extraction\n", "# Skip this step since trait_row is None (no useful clinical data available for our analysis)\n", "# We determined this dataset doesn't have the necessary trait variability for our study\n" ] }, { "cell_type": "markdown", "id": "d7634a46", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "401df356", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:04:03.825542Z", "iopub.status.busy": "2025-03-25T06:04:03.825427Z", "iopub.status.idle": "2025-03-25T06:04:04.277312Z", "shell.execute_reply": "2025-03-25T06:04:04.276931Z" } }, "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: 138745\n", "First 20 gene/probe identifiers:\n", "Index(['AFFX-BkGr-GC03_st', 'AFFX-BkGr-GC04_st', 'AFFX-BkGr-GC05_st',\n", " 'AFFX-BkGr-GC06_st', 'AFFX-BkGr-GC07_st', 'AFFX-BkGr-GC08_st',\n", " 'AFFX-BkGr-GC09_st', 'AFFX-BkGr-GC10_st', 'AFFX-BkGr-GC11_st',\n", " 'AFFX-BkGr-GC12_st', 'AFFX-BkGr-GC13_st', 'AFFX-BkGr-GC14_st',\n", " 'AFFX-BkGr-GC15_st', 'AFFX-BkGr-GC16_st', 'AFFX-BkGr-GC17_st',\n", " 'AFFX-BkGr-GC18_st', 'AFFX-BkGr-GC19_st', 'AFFX-BkGr-GC20_st',\n", " 'AFFX-BkGr-GC21_st', 'AFFX-BkGr-GC22_st'],\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": "d1857353", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "f95508b9", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:04:04.278733Z", "iopub.status.busy": "2025-03-25T06:04:04.278611Z", "iopub.status.idle": "2025-03-25T06:04:04.280619Z", "shell.execute_reply": "2025-03-25T06:04:04.280302Z" } }, "outputs": [], "source": [ "# These identifiers, starting with \"AFFX-\", appear to be from Affymetrix microarray probes\n", "# They're not standard human gene symbols and will need to be mapped to gene symbols\n", "# The \"AFFX-\" prefix is typically used for Affymetrix control probes, and the \"_st\" suffix\n", "# indicates these are likely from a newer generation Affymetrix array\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "ea415ba1", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "063607b8", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:04:04.281860Z", "iopub.status.busy": "2025-03-25T06:04:04.281752Z", "iopub.status.idle": "2025-03-25T06:04:23.826678Z", "shell.execute_reply": "2025-03-25T06:04:23.826095Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene annotation preview:\n", "{'ID': ['TC0100006432.hg.1', 'TC0100006433.hg.1', 'TC0100006434.hg.1', 'TC0100006435.hg.1', 'TC0100006436.hg.1'], 'probeset_id': ['TC0100006432.hg.1', 'TC0100006433.hg.1', 'TC0100006434.hg.1', 'TC0100006435.hg.1', 'TC0100006436.hg.1'], 'seqname': ['chr1', 'chr1', 'chr1', 'chr1', 'chr1'], 'strand': ['+', '+', '+', '+', '+'], 'start': ['11869', '28046', '29554', '52473', '62948'], 'stop': ['14412', '29178', '31109', '53312', '63887'], 'total_probes': [10.0, 6.0, 10.0, 10.0, 10.0], 'gene_assignment': ['NR_046018 // DDX11L1 // DEAD/H (Asp-Glu-Ala-Asp/His) box helicase 11 like 1 // 1p36.33 // 100287102 /// OTTHUMT00000002844 // DDX11L1 // DEAD/H (Asp-Glu-Ala-Asp/His) box helicase 11 like 1 // 1p36.33 // 100287102 /// OTTHUMT00000362751 // DDX11L1 // DEAD/H (Asp-Glu-Ala-Asp/His) box helicase 11 like 1 // 1p36.33 // 100287102', 'spopoybu.aAug10-unspliced // spopoybu // Transcript Identified by AceView // --- // ---', 'NR_036267 // MIR1302-10 // microRNA 1302-10 // --- // 100422834 /// ENST00000607096 // MIR1302-2 // microRNA 1302-2 // --- // 100302278', 'OTTHUMT00000471235 // OR4G4P // olfactory receptor, family 4, subfamily G, member 4 pseudogene // 1p36.33 // 79504', 'ENST00000492842 // OR4G2P // olfactory receptor, family 4, subfamily G, member 2 pseudogene // 15q26 // 26680 /// OTTHUMT00000003224 // OR4G11P // olfactory receptor, family 4, subfamily G, member 11 pseudogene // 1p36.33 // 403263'], '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 /// OTTHUMT00000002844 // Havana transcript // DEAD/H (Asp-Glu-Ala-Asp/His) box helicase 11 like 1[gene_biotype:transcribed_unprocessed_pseudogene transcript_biotype:transcribed_unprocessed_pseudogene] // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000362751 // Havana transcript // DEAD/H (Asp-Glu-Ala-Asp/His) box helicase 11 like 1[gene_biotype:transcribed_unprocessed_pseudogene transcript_biotype:processed_transcript] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000450305 // ENSEMBL // DEAD/H (Asp-Glu-Ala-Asp/His) box helicase 11 like 1 [gene_biotype:transcribed_unprocessed_pseudogene transcript_biotype:transcribed_unprocessed_pseudogene] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000456328 // ENSEMBL // DEAD/H (Asp-Glu-Ala-Asp/His) box helicase 11 like 1 [gene_biotype:transcribed_unprocessed_pseudogene transcript_biotype:processed_transcript] // chr1 // 100 // 100 // 0 // --- // 0 /// NONHSAT000001 // lncRNAWiki // Non-coding transcript identified by NONCODE // chr1 // 100 // 100 // 0 // --- // 0 /// NONHSAT000001 // NONCODE // Non-coding transcript identified by NONCODE: Linc // chr1 // 100 // 100 // 0 // --- // 0 /// NONHSAT000002 // lncRNAWiki // Non-coding transcript identified by NONCODE // chr1 // 100 // 100 // 0 // --- // 0 /// NONHSAT000002 // NONCODE // Non-coding transcript identified by NONCODE: Linc // chr1 // 100 // 100 // 0 // --- // 0 /// NONHSAT000003 // lncRNAWiki // Non-coding transcript identified by NONCODE // chr1 // 100 // 100 // 0 // --- // 0 /// NONHSAT000003 // NONCODE // Non-coding transcript identified by NONCODE: Linc // chr1 // 100 // 100 // 0 // --- // 0 /// NONHSAT000004 // lncRNAWiki // Non-coding transcript identified by NONCODE // chr1 // 100 // 100 // 0 // --- // 0 /// NONHSAT000004 // NONCODE // Non-coding transcript identified by NONCODE: Linc // chr1 // 100 // 100 // 0 // --- // 0', 'spopoybu.aAug10-unspliced // Ace View // Transcript Identified by AceView // chr1 // 100 // 100 // 0 // --- // 0', 'NR_036267 // RefSeq // Homo sapiens microRNA 1302-10 (MIR1302-10), microRNA. // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000607096 // ENSEMBL // microRNA 1302-2 [gene_biotype:miRNA transcript_biotype:miRNA] // chr1 // 100 // 100 // 0 // --- // 0 /// NR_036051_3 // RefSeq // Homo sapiens microRNA 1302-2 (MIR1302-2), microRNA. // chr1 // 100 // 100 // 0 // --- // 0 /// NR_036266_3 // RefSeq // Homo sapiens microRNA 1302-9 (MIR1302-9), microRNA. // chr1 // 100 // 100 // 0 // --- // 0 /// NR_036268_4 // RefSeq // Homo sapiens microRNA 1302-11 (MIR1302-11), microRNA. // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000469289 // ENSEMBL // havana:known chromosome:GRCh38:1:30267:31109:1 gene:ENSG00000243485 gene_biotype:lincRNA transcript_biotype:lincRNA // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000473358 // ENSEMBL // havana:known chromosome:GRCh38:1:29554:31097:1 gene:ENSG00000243485 gene_biotype:lincRNA transcript_biotype:lincRNA // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000469289.1 // lncRNAWiki // microRNA 1302-11 [Source:HGNC Symbol;Acc:HGNC:38246] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000473358.1 // lncRNAWiki // microRNA 1302-11 [Source:HGNC Symbol;Acc:HGNC:38246] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000607096.1 // lncRNAWiki // microRNA 1302-11 [Source:HGNC Symbol;Acc:38246] // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000002840 // Havana transcript // novel transcript // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000002841 // Havana transcript // novel transcript // chr1 // 100 // 100 // 0 // --- // 0 /// uc031tlb.1 // UCSC Genes // microRNA 1302-2 [Source:HGNC Symbol;Acc:HGNC:35294] // chr1 // 100 // 100 // 0 // --- // 0 /// uc057aty.1 // UCSC Genes // N/A // chr1 // 100 // 100 // 0 // --- // 0 /// uc057atz.1 // UCSC Genes // N/A // chr1 // 100 // 100 // 0 // --- // 0 /// HG491497.1:1..712:ncRNA // RNACentral // long non-coding RNA OTTHUMT00000002840.1 (RP11-34P13.3 gene // chr1 // 100 // 100 // 0 // --- // 0 /// HG491498.1:1..535:ncRNA // RNACentral // long non-coding RNA OTTHUMT00000002841.2 (RP11-34P13.3 gene // chr1 // 100 // 100 // 0 // --- // 0 /// LM610125.1:1..138:precursor_RNA // RNACentral // microRNA hsa-mir-1302-9 precursor // chr1 // 100 // 100 // 0 // --- // 0 /// NONHSAT000011 // NONCODE // Non-coding transcript identified by NONCODE: Linc // chr1 // 100 // 100 // 0 // --- // 0 /// NONHSAT000012 // NONCODE // Non-coding transcript identified by NONCODE: Linc // chr1 // 100 // 100 // 0 // --- // 0 /// NR_036051.1:1..138:precursor_RNA // RNACentral // microRNA hsa-mir-1302-9 precursor // chr1 // 100 // 100 // 0 // --- // 0', 'OTTHUMT00000471235 // Havana transcript // lfactory receptor, family 4, subfamily G, member 4 pseudogene[gene_biotype:unprocessed_pseudogene transcript_biotype:unprocessed_pseudogene] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000606857 // ENSEMBL // olfactory receptor, family 4, subfamily G, member 4 pseudogene [gene_biotype:unprocessed_pseudogene transcript_biotype:unprocessed_pseudogene] // chr1 // 100 // 100 // 0 // --- // 0', 'ENST00000492842 // ENSEMBL // olfactory receptor, family 4, subfamily G, member 11 pseudogene [gene_biotype:unprocessed_pseudogene transcript_biotype:unprocessed_pseudogene] // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000003224 // Havana transcript // olfactory receptor, family 4, subfamily G, member 11 pseudogene[gene_biotype:unprocessed_pseudogene transcript_biotype:unprocessed_pseudogene] // chr1 // 100 // 100 // 0 // --- // 0 /// NONHSAT000016 // lncRNAWiki // Non-coding transcript identified by NONCODE // chr1 // 100 // 100 // 0 // --- // 0 /// NONHSAT000016 // NONCODE // Non-coding transcript identified by NONCODE: Linc // chr1 // 100 // 100 // 0 // --- // 0'], 'swissprot': ['NR_046018 // B7ZGX0 /// NR_046018 // B7ZGX2 /// NR_046018 // B7ZGX7 /// NR_046018 // B7ZGX8 /// OTTHUMT00000002844 // B7ZGX0 /// OTTHUMT00000002844 // B7ZGX2 /// OTTHUMT00000002844 // B7ZGX7 /// OTTHUMT00000002844 // B7ZGX8 /// OTTHUMT00000362751 // B7ZGX0 /// OTTHUMT00000362751 // B7ZGX2 /// OTTHUMT00000362751 // B7ZGX7 /// OTTHUMT00000362751 // B7ZGX8 /// ENST00000450305 // B7ZGX0 /// ENST00000450305 // B7ZGX2 /// ENST00000450305 // B7ZGX7 /// ENST00000450305 // B7ZGX8 /// ENST00000450305 // B4E2Z4 /// ENST00000450305 // B7ZGW9 /// ENST00000450305 // Q6ZU42 /// ENST00000450305 // B7ZGX3 /// ENST00000450305 // B5WYT6 /// ENST00000456328 // B7ZGX0 /// ENST00000456328 // B7ZGX2 /// ENST00000456328 // B7ZGX7 /// ENST00000456328 // B7ZGX8 /// ENST00000456328 // B4E2Z4 /// ENST00000456328 // B7ZGW9 /// ENST00000456328 // Q6ZU42 /// ENST00000456328 // B7ZGX3 /// ENST00000456328 // B5WYT6', '---', '---', '---', '---'], 'unigene': ['NR_046018 // Hs.714157 // testis| normal| adult /// OTTHUMT00000002844 // Hs.714157 // testis| normal| adult /// OTTHUMT00000362751 // Hs.714157 // testis| normal| adult /// ENST00000450305 // Hs.719844 // brain| testis| normal /// ENST00000450305 // Hs.714157 // testis| normal| adult /// ENST00000450305 // Hs.740212 // --- /// ENST00000450305 // Hs.712940 // bladder| bone marrow| brain| embryonic tissue| intestine| mammary gland| muscle| pharynx| placenta| prostate| skin| spleen| stomach| testis| thymus| breast (mammary gland) tumor| gastrointestinal tumor| glioma| non-neoplasia| normal| prostate cancer| skin tumor| soft tissue/muscle tissue tumor|embryoid body| adult /// ENST00000456328 // Hs.719844 // brain| testis| normal /// ENST00000456328 // Hs.714157 // testis| normal| adult /// ENST00000456328 // Hs.740212 // --- /// ENST00000456328 // Hs.712940 // bladder| bone marrow| brain| embryonic tissue| intestine| mammary gland| muscle| pharynx| placenta| prostate| skin| spleen| stomach| testis| thymus| breast (mammary gland) tumor| gastrointestinal tumor| glioma| non-neoplasia| normal| prostate cancer| skin tumor| soft tissue/muscle tissue tumor|embryoid body| adult', '---', '---', '---', '---'], 'GO_biological_process': ['ENST00000450305 // GO:0006139 // nucleobase-containing compound metabolic process // inferred from electronic annotation /// ENST00000456328 // GO:0006139 // nucleobase-containing compound metabolic process // inferred from electronic annotation', '---', '---', '---', '---'], 'GO_cellular_component': ['---', '---', '---', '---', '---'], 'GO_molecular_function': ['ENST00000450305 // GO:0003676 // nucleic acid binding // inferred from electronic annotation /// ENST00000450305 // GO:0005524 // ATP binding // inferred from electronic annotation /// ENST00000450305 // GO:0008026 // ATP-dependent helicase activity // inferred from electronic annotation /// ENST00000450305 // GO:0016818 // hydrolase activity, acting on acid anhydrides, in phosphorus-containing anhydrides // inferred from electronic annotation /// ENST00000456328 // GO:0003676 // nucleic acid binding // inferred from electronic annotation /// ENST00000456328 // GO:0005524 // ATP binding // inferred from electronic annotation /// ENST00000456328 // GO:0008026 // ATP-dependent helicase activity // inferred from electronic annotation /// ENST00000456328 // GO:0016818 // hydrolase activity, acting on acid anhydrides, in phosphorus-containing anhydrides // inferred from electronic annotation', '---', '---', '---', '---'], 'pathway': ['---', '---', '---', '---', '---'], 'protein_domains': ['---', '---', '---', '---', '---'], 'category': ['main', 'main', 'main', 'main', 'main'], 'locus type': ['Multiple_Complex', 'Coding', 'Multiple_Complex', 'Pseudogene', 'Multiple_Complex'], 'SPOT_ID': ['NR_046018 // RefSeq', 'spopoybu.aAug10-unspliced // Ace View', 'NR_036267 // RefSeq', 'OTTHUMT00000471235 // Havana transcript', 'ENST00000492842 // ENSEMBL']}\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": "3f1bd8df", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "f2d8f9f1", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:04:23.828552Z", "iopub.status.busy": "2025-03-25T06:04:23.828401Z", "iopub.status.idle": "2025-03-25T06:04:28.932792Z", "shell.execute_reply": "2025-03-25T06:04:28.932111Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Mapped gene expression data shape: (34003, 38)\n", "First few gene symbols: ['A1BG', 'A1BG-AS1', 'A1CF', 'A2M', 'A2M-AS1']\n", "Number of columns (samples): 38\n" ] } ], "source": [ "# 1. Based on the gene identifiers and gene annotation data:\n", "# Gene expression data uses Affymetrix IDs like \"AFFX-BkGr-GC03_st\"\n", "# The gene annotation data uses \"ID\" or \"probeset_id\" for identifiers\n", "# For gene symbols, we need to extract them from the \"gene_assignment\" column\n", "\n", "# 2. Extract mapping between probe IDs and gene symbols\n", "# Create mapping dataframe with relevant columns\n", "mapping_df = gene_annotation[['ID', 'gene_assignment']].copy()\n", "# Rename 'gene_assignment' to 'Gene' to match the expected column name in apply_gene_mapping function\n", "mapping_df = mapping_df.rename(columns={'gene_assignment': 'Gene'})\n", "\n", "# 3. Apply gene mapping to convert probe-level measurements to gene expression\n", "# First make sure the gene expression data is loaded\n", "if 'gene_data' not in locals():\n", " gene_data = get_genetic_data(matrix_file)\n", " \n", "# Apply the mapping function to convert probes to genes\n", "gene_data = apply_gene_mapping(gene_data, mapping_df)\n", "\n", "# Normalize gene symbols to ensure consistency\n", "gene_data = normalize_gene_symbols_in_index(gene_data)\n", "\n", "# Print information about the resulting gene expression data\n", "print(f\"Mapped gene expression data shape: {gene_data.shape}\")\n", "print(f\"First few gene symbols: {gene_data.index[:5].tolist()}\")\n", "print(f\"Number of columns (samples): {len(gene_data.columns)}\")\n" ] }, { "cell_type": "markdown", "id": "f85839a2", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "b391360a", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:04:28.935068Z", "iopub.status.busy": "2025-03-25T06:04:28.934912Z", "iopub.status.idle": "2025-03-25T06:04:44.009744Z", "shell.execute_reply": "2025-03-25T06:04:44.009356Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data saved to ../../output/preprocess/Ovarian_Cancer/gene_data/GSE146964.csv\n", "Sample IDs from gene data: 38 samples\n", "Clinical data shape: (1, 38)\n", "Clinical data saved to ../../output/preprocess/Ovarian_Cancer/clinical_data/GSE146964.csv\n", "Shape of linked data: (38, 34004)\n", "Handling missing values...\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "/media/techt/DATA/GenoAgent/tools/preprocess.py:455: FutureWarning: Downcasting object dtype arrays on .fillna, .ffill, .bfill is deprecated and will change in a future version. Call result.infer_objects(copy=False) instead. To opt-in to the future behavior, set `pd.set_option('future.no_silent_downcasting', True)`\n", " df[gene_cols] = df[gene_cols].fillna(df[gene_cols].mean())\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Shape of linked data after handling missing values: (38, 34004)\n", "Checking for bias in features...\n", "Quartiles for 'Ovarian_Cancer':\n", " 25%: 1.0\n", " 50% (Median): 1.0\n", " 75%: 1.0\n", "Min: 1\n", "Max: 1\n", "The distribution of the feature 'Ovarian_Cancer' in this dataset is severely biased.\n", "\n", "Dataset validation failed due to trait bias. Final linked data not saved.\n" ] } ], "source": [ "# 1. Since we already normalized gene symbols in the previous step (6),\n", "# we can use the gene_data that was already processed\n", "\n", "# Save the gene 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", "\n", "# 2. Since we determined in step 2 that there's no usable trait variation \n", "# (all samples are cancer cases with no controls), we'll create a clinical dataframe\n", "# but note this limitation\n", "\n", "# Create a clinical dataframe with the trait (Ovarian_Cancer)\n", "sample_ids = gene_data.columns.tolist()\n", "print(f\"Sample IDs from gene data: {len(sample_ids)} samples\")\n", "\n", "# Create clinical dataframe, but note that all samples have the same trait value\n", "clinical_df = pd.DataFrame(index=[trait], columns=sample_ids)\n", "clinical_df.loc[trait] = 1 # All samples are ovarian cancer tumors\n", "\n", "print(f\"Clinical data shape: {clinical_df.shape}\")\n", "\n", "# Save the clinical data\n", "os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", "clinical_df.to_csv(out_clinical_data_file)\n", "print(f\"Clinical data saved to {out_clinical_data_file}\")\n", "\n", "# 3. Link clinical and genetic data\n", "linked_data = geo_link_clinical_genetic_data(clinical_df, gene_data)\n", "print(f\"Shape of linked data: {linked_data.shape}\")\n", "\n", "# 4. Handle missing values in the linked data\n", "print(\"Handling missing values...\")\n", "linked_data_cleaned = handle_missing_values(linked_data, trait)\n", "print(f\"Shape of linked data after handling missing values: {linked_data_cleaned.shape}\")\n", "\n", "# 5. Check if the trait and demographic features are biased\n", "print(\"Checking for bias in features...\")\n", "is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data_cleaned, trait)\n", "\n", "# 6. Validate the dataset and save cohort information\n", "note = \"Dataset contains expression data for ovarian cancer tumors. All samples are tumor samples with no controls, so trait bias is expected and the dataset is not suitable for case-control analysis.\"\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=note\n", ")\n", "\n", "# 7. Save the linked data if it's usable (though we expect it won't be due to trait bias)\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 due to trait bias. 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 }