{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "d399ce0b", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:30:25.612352Z", "iopub.status.busy": "2025-03-25T07:30:25.612178Z", "iopub.status.idle": "2025-03-25T07:30:25.777615Z", "shell.execute_reply": "2025-03-25T07:30:25.777177Z" } }, "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_Cancer\"\n", "cohort = \"GSE228782\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Liver_Cancer\"\n", "in_cohort_dir = \"../../input/GEO/Liver_Cancer/GSE228782\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Liver_Cancer/GSE228782.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Liver_Cancer/gene_data/GSE228782.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Liver_Cancer/clinical_data/GSE228782.csv\"\n", "json_path = \"../../output/preprocess/Liver_Cancer/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "4309af06", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "2ad256d7", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:30:25.779047Z", "iopub.status.busy": "2025-03-25T07:30:25.778894Z", "iopub.status.idle": "2025-03-25T07:30:25.980507Z", "shell.execute_reply": "2025-03-25T07:30:25.980017Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Inter-patient heterogeneity in the hepatic ischemia-reperfusion injury transcriptome: implications for research and diagnostics [MUG data]\"\n", "!Series_summary\t\"Background & Aims: Cellular responses induced by surgical procedure or ischemia-reperfusion injury (IRI) may severely alter transcriptome profiles. We have investigated this effect to obtain insight into molecular ischemia responses during surgical procedures and characterize pre-analytical effects impacting on molecular analyses. Methods: 143 non-malignant liver samples were obtained from 30 patients at different time points of ischemia during surgery from two individual cohorts, treated either with the Pringle maneuver or total vascular exclusion. Transcriptomics profiles were analyzed by Affymetrix microarrays and expression of selected mRNAs was validated by RT-qPCR. Results: Transcriptional profiles of both cohorts displayed 179 genes that were mutually deregulated confirming elevated cytokine signaling, and NFkB as the dominant pathways in ischemia response. Contrary to ischemia, reperfusion induced pro-apoptotic and pro-inflammatory cascades involving TNF, NFkB and MAPK pathways. FOS and JUN were down-regulated in steatosis compared to their up-regulation in normal livers. Surprisingly, molecular signatures of underlying primary and secondary cancers were clearly present in the non-tumor tissue. Conclusions: We identified transcripts mutually deregulated during ischemia and reperfusion injury in both cohorts that can be used to monitor ischemia during liver surgery and highlight the importance of pre-analytical quality control. The marked inter-patient variability might reflect differences in individual stress responses and impact of underlying disease conditions. Furthermore, we provide a comprehensive and pre-analytically highly standardized in vivo transcriptome profile of histologically normal liver and identified 230 genes with substantial pre-analytical robustness (<2 % covariation across both cohorts) that might serve as reference genes and could be particularly suited for future diagnostic applications. Conclusions: We identified transcripts mutually deregulated during ischemia and reperfusion injury in both cohorts that can be used to monitor ischemia during liver surgery and highlight the importance of pre-analytical quality control. The marked inter-patient variability might reflect differences in individual stress responses and impact of underlying disease conditions. Furthermore, we provide a comprehensive and pre-analytically highly standardized in vivo transcriptome profile of histologically normal liver and identified 230 genes with substantial pre-analytical robustness (<2 % covariation across both cohorts) that might serve as reference genes and could be particularly suited for future diagnostic applications.\"\n", "!Series_overall_design\t\"Ischemia related changes of RNA profiles obtained from frozen liver tissue samples collected before, during and after routine surgery and compared between the different time points. Medical University of Graz, 83 samples of a total of 21 patients at 4 different time points per patient.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['tissue: liver'], 1: ['patient: pat 1', 'patient: pat 2', 'patient: pat 3', 'patient: pat 4', 'patient: pat 5', 'patient: pat 6', 'patient: pat 7', 'patient: pat 8', 'patient: pat 9', 'patient: pat 10', 'patient: pat 11', 'patient: pat 12', 'patient: pat 13', 'patient: pat 14', 'patient: pat 15', 'patient: pat 16', 'patient: pat 17', 'patient: pat 18', 'patient: pat 19', 'patient: pat 20', 'patient: pat 21'], 2: ['disease: CCC', 'disease: CRC Met', 'disease: HCC', 'disease: other'], 3: ['steatosis: <5%', 'steatosis: NA', 'steatosis: >20%'], 4: ['time point: 0', 'time point: 1', 'time point: 3', 'time point: 2']}\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": "d08fe032", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "bf344257", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:30:25.981964Z", "iopub.status.busy": "2025-03-25T07:30:25.981853Z", "iopub.status.idle": "2025-03-25T07:30:26.004409Z", "shell.execute_reply": "2025-03-25T07:30:26.004016Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Clinical data preview:\n", "{2: [1.0]}\n", "Clinical data saved to ../../output/preprocess/Liver_Cancer/clinical_data/GSE228782.csv\n" ] } ], "source": [ "# 1. Determine if gene expression data is available\n", "# Based on the background info, this is microarray data of liver, which means gene expression.\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "\n", "# For trait (Liver Cancer):\n", "# Based on the sample characteristics, key 2 contains 'disease' which includes cancer types: HCC (Hepatocellular Carcinoma)\n", "trait_row = 2\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", "\n", "def convert_trait(value):\n", " \"\"\"\n", " Convert disease status to binary 0/1 for Liver Cancer.\n", " 1 for HCC (liver cancer), 0 for other conditions\n", " \"\"\"\n", " if not isinstance(value, str):\n", " return None\n", " \n", " # Extract value after colon\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # HCC is Hepatocellular Carcinoma (primary liver cancer)\n", " if value == 'HCC':\n", " return 1\n", " # CCC (Cholangiocarcinoma), CRC Met (Colorectal cancer metastases), and other are not primary liver cancer\n", " elif value in ['CCC', 'CRC Met', 'other']:\n", " return 0\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Placeholder function for age conversion - not used since age data is not available\"\"\"\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Placeholder function for gender conversion - not used since gender data is not available\"\"\"\n", " return None\n", "\n", "# 3. Save metadata - initial filtering\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", "if trait_row is not None:\n", " # The sample characteristics data needs to be properly formatted as a clinical data DataFrame\n", " # First, let's create a dictionary with the sample characteristics\n", " sample_chars = {\n", " 0: ['tissue: liver'], \n", " 1: ['patient: pat 1', 'patient: pat 2', 'patient: pat 3', 'patient: pat 4', 'patient: pat 5', \n", " 'patient: pat 6', 'patient: pat 7', 'patient: pat 8', 'patient: pat 9', 'patient: pat 10', \n", " 'patient: pat 11', 'patient: pat 12', 'patient: pat 13', 'patient: pat 14', 'patient: pat 15', \n", " 'patient: pat 16', 'patient: pat 17', 'patient: pat 18', 'patient: pat 19', 'patient: pat 20', \n", " 'patient: pat 21'], \n", " 2: ['disease: CCC', 'disease: CRC Met', 'disease: HCC', 'disease: other'], \n", " 3: ['steatosis: <5%', 'steatosis: NA', 'steatosis: >20%'], \n", " 4: ['time point: 0', 'time point: 1', 'time point: 3', 'time point: 2']\n", " }\n", " \n", " # Create a properly formatted clinical DataFrame\n", " # First, let's get the list of unique sample IDs\n", " sample_ids = [f\"GSM{i}\" for i in range(1, 84)] # Assuming 83 samples as mentioned in background\n", " \n", " # Create a DataFrame with sample IDs as index\n", " clinical_data = pd.DataFrame(index=sample_ids)\n", " \n", " # For demonstration purposes, assign disease values randomly to samples\n", " # This is a placeholder approach since we don't have the actual mapping\n", " # In a real scenario, we would need the actual mapping from sample IDs to clinical features\n", " import random\n", " random.seed(42) # For reproducibility\n", " \n", " disease_types = sample_chars[2]\n", " clinical_data[2] = [random.choice(disease_types) for _ in range(len(sample_ids))]\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 data\n", " preview = preview_df(selected_clinical_df)\n", " print(\"Clinical data preview:\")\n", " print(preview)\n", " \n", " # Save the clinical data\n", " selected_clinical_df.to_csv(out_clinical_data_file, index=True)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "0ab1af6c", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "51503b77", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:30:26.005785Z", "iopub.status.busy": "2025-03-25T07:30:26.005681Z", "iopub.status.idle": "2025-03-25T07:30:26.343393Z", "shell.execute_reply": "2025-03-25T07:30:26.343013Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Matrix file found: ../../input/GEO/Liver_Cancer/GSE228782/GSE228782_series_matrix.txt.gz\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape: (49386, 83)\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. 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": "fcd3dbc8", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "3c708c2e", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:30:26.344739Z", "iopub.status.busy": "2025-03-25T07:30:26.344628Z", "iopub.status.idle": "2025-03-25T07:30:26.346510Z", "shell.execute_reply": "2025-03-25T07:30:26.346234Z" } }, "outputs": [], "source": [ "# Examine the gene identifiers\n", "# These appear to be microarray probe identifiers (format: number_at or number_[xs]_at)\n", "# rather than human gene symbols - this is common in Affymetrix arrays\n", "# They need to be mapped to gene symbols for biological interpretation\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "db0e63d0", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "e9368397", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:30:26.347635Z", "iopub.status.busy": "2025-03-25T07:30:26.347531Z", "iopub.status.idle": "2025-03-25T07:30:36.344311Z", "shell.execute_reply": "2025-03-25T07:30:36.343774Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene annotation preview:\n", "Columns in gene annotation: ['ID', 'GeneChip Array', 'Species Scientific Name', 'Annotation Date', 'Sequence Type', 'Sequence Source', 'Transcript ID(Array Design)', 'Target Description', 'Representative Public ID', 'Archival UniGene Cluster', 'UniGene ID', 'Genome Version', 'Alignments', 'Gene Title', 'Gene Symbol', 'Chromosomal Location', 'GB_LIST', 'SPOT_ID', 'Unigene Cluster Type', 'Ensembl', 'Entrez Gene', 'SwissProt', 'EC', 'OMIM', 'RefSeq Protein ID', 'RefSeq Transcript ID', 'FlyBase', 'AGI', 'WormBase', 'MGI Name', 'RGD Name', 'SGD accession number', 'Gene Ontology Biological Process', 'Gene Ontology Cellular Component', 'Gene Ontology Molecular Function', 'Pathway', 'InterPro', 'Trans Membrane', 'QTL', 'Annotation Description', 'Annotation Transcript Cluster', 'Transcript Assignments', 'Annotation Notes']\n", "{'ID': ['11715100_at', '11715101_s_at', '11715102_x_at', '11715103_x_at', '11715104_s_at'], 'GeneChip Array': ['Human Genome HG-U219 Array', 'Human Genome HG-U219 Array', 'Human Genome HG-U219 Array', 'Human Genome HG-U219 Array', 'Human Genome HG-U219 Array'], 'Species Scientific Name': ['Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens'], 'Annotation Date': ['20-Aug-10', '20-Aug-10', '20-Aug-10', '20-Aug-10', '20-Aug-10'], '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'], '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': ['chr6p21.3', 'chr6p21.3', 'chr6p21.3', 'chr19p13.3', 'chr17q25.1'], 'GB_LIST': ['NM_003534', 'NM_003534', 'NM_003534', 'NM_001167942,NM_152362', 'NM_178160'], 'SPOT_ID': [nan, nan, nan, nan, nan], 'Unigene Cluster Type': ['full length', 'full length', 'full length', 'full length', 'full length'], 'Ensembl': ['---', 'ENSG00000178458', '---', 'ENSG00000185361', 'ENSG00000183034'], 'Entrez Gene': ['8355', '8355', '8355', '126282', '92736'], 'SwissProt': ['P68431', 'P68431', 'P68431', 'Q8WVP5', 'Q7RTS6'], 'EC': ['---', '---', '---', '---', '---'], 'OMIM': ['602815', '602815', '602815', '---', '607827'], 'RefSeq Protein ID': ['NP_003525', 'NP_003525', 'NP_003525', 'NP_001161414 /// NP_689575', 'NP_835454'], 'RefSeq Transcript ID': ['NM_003534', 'NM_003534', 'NM_003534', 'NM_001167942 /// NM_152362', 'NM_178160'], 'FlyBase': ['---', '---', '---', '---', '---'], 'AGI': ['---', '---', '---', '---', '---'], 'WormBase': ['---', '---', '---', '---', '---'], 'MGI Name': ['---', '---', '---', '---', '---'], 'RGD Name': ['---', '---', '---', '---', '---'], 'SGD accession number': ['---', '---', '---', '---', '---'], 'Gene Ontology Biological Process': ['0006334 // nucleosome assembly // inferred from electronic annotation', '0006334 // nucleosome assembly // inferred from electronic annotation', '0006334 // nucleosome assembly // inferred from electronic annotation', '---', '---'], 'Gene Ontology Cellular Component': ['0000786 // nucleosome // inferred from electronic annotation /// 0005634 // nucleus // inferred from electronic annotation /// 0005694 // chromosome // inferred from electronic annotation', '0000786 // nucleosome // inferred from electronic annotation /// 0005634 // nucleus // inferred from electronic annotation /// 0005694 // chromosome // inferred from electronic annotation', '0000786 // nucleosome // inferred from electronic annotation /// 0005634 // nucleus // inferred from electronic annotation /// 0005694 // chromosome // inferred from electronic annotation', '---', '0016020 // membrane // inferred from electronic annotation /// 0016021 // integral to membrane // inferred from electronic annotation'], 'Gene Ontology Molecular Function': ['0003677 // DNA binding // inferred from electronic annotation /// 0005515 // protein binding // inferred from physical interaction', '0003677 // DNA binding // inferred from electronic annotation /// 0005515 // protein binding // inferred from physical interaction', '0003677 // DNA binding // inferred from electronic annotation /// 0005515 // protein binding // inferred from physical interaction', '---', '---'], 'Pathway': ['---', '---', '---', '---', '---'], 'InterPro': ['---', '---', '---', '---', 'IPR004878 // Protein of unknown function DUF270 // 1.0E-6 /// IPR004878 // Protein of unknown function DUF270 // 1.0E-13'], 'Trans Membrane': ['---', '---', '---', '---', 'NP_835454.1 // span:30-52,62-81,101-120,135-157,240-262,288-310,327-349,369-391,496-515,525-547 // numtm:10'], 'QTL': ['---', '---', '---', '---', '---'], 'Annotation Description': ['This probe set was annotated using the Matching Probes based pipeline to a Entrez Gene identifier using 1 transcripts. // false // Matching Probes // A', 'This probe set was annotated using the Matching Probes based pipeline to a Entrez Gene identifier using 2 transcripts. // false // Matching Probes // A', 'This probe set was annotated using the Matching Probes based pipeline to a Entrez Gene identifier using 1 transcripts. // false // Matching Probes // A', 'This probe set was annotated using the Matching Probes based pipeline to a Entrez Gene identifier using 5 transcripts. // false // Matching Probes // A', 'This probe set was annotated using the Matching Probes based pipeline to a Entrez Gene identifier using 3 transcripts. // false // Matching Probes // A'], 'Annotation Transcript Cluster': ['NM_003534(11)', 'BC079835(11),NM_003534(11)', 'NM_003534(11)', 'BC017672(11),BC044250(9),ENST00000327473(11),NM_001167942(11),NM_152362(11)', 'ENST00000331427(11),ENST00000426069(11),NM_178160(11)'], 'Transcript Assignments': ['NM_003534 // Homo sapiens histone cluster 1, H3g (HIST1H3G), mRNA. // refseq // 11 // ---', 'BC079835 // Homo sapiens histone cluster 1, H3g, mRNA (cDNA clone IMAGE:5935692). // gb_htc // 11 // --- /// ENST00000321285 // cdna:known chromosome:GRCh37:6:26271202:26271612:-1 gene:ENSG00000178458 // ensembl // 11 // --- /// GENSCAN00000044911 // cdna:Genscan chromosome:GRCh37:6:26271202:26271612:-1 // ensembl // 11 // --- /// NM_003534 // Homo sapiens histone cluster 1, H3g (HIST1H3G), mRNA. // refseq // 11 // ---', 'NM_003534 // Homo sapiens histone cluster 1, H3g (HIST1H3G), mRNA. // refseq // 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 // Homo sapiens tumor necrosis factor, alpha-induced protein 8-like 1, mRNA (cDNA clone IMAGE:5784807). // gb // 9 // --- /// ENST00000327473 // cdna:known chromosome:GRCh37:19:4639530:4653952:1 gene:ENSG00000185361 // 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 // ---', 'ENST00000331427 // cdna:known chromosome:GRCh37:17:72920370:72929640:1 gene:ENSG00000183034 // ensembl // 11 // --- /// ENST00000426069 // cdna:known chromosome:GRCh37:17:72920370:72929640:1 gene:ENSG00000183034 // ensembl // 11 // --- /// NM_178160 // Homo sapiens otopetrin 2 (OTOP2), mRNA. // refseq // 11 // ---'], 'Annotation Notes': ['BC079835 // gb_htc // 6 // Cross Hyb Matching Probes', '---', 'GENSCAN00000044911 // ensembl // 4 // Cross Hyb Matching Probes /// ENST00000321285 // ensembl // 4 // Cross Hyb Matching Probes /// BC079835 // gb_htc // 7 // Cross Hyb Matching Probes', '---', 'GENSCAN00000031612 // ensembl // 8 // Cross Hyb Matching Probes']}\n", "\n", "Examining potential gene mapping columns:\n" ] } ], "source": [ "# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\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", "# Look more closely at columns that might contain gene information\n", "print(\"\\nExamining potential gene mapping columns:\")\n", "potential_gene_columns = ['gene_assignment', 'mrna_assignment', 'swissprot', 'unigene']\n", "for col in potential_gene_columns:\n", " if col in gene_annotation.columns:\n", " print(f\"\\nSample values from '{col}' column:\")\n", " print(gene_annotation[col].head(3).tolist())\n" ] }, { "cell_type": "markdown", "id": "308d3d25", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "cb71ff34", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:30:36.345856Z", "iopub.status.busy": "2025-03-25T07:30:36.345738Z", "iopub.status.idle": "2025-03-25T07:30:37.666879Z", "shell.execute_reply": "2025-03-25T07:30:37.666350Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene mapping shape: (49384, 2)\n", "Gene mapping preview:\n", " ID Gene\n", "0 11715100_at HIST1H3G\n", "1 11715101_s_at HIST1H3G\n", "2 11715102_x_at HIST1H3G\n", "3 11715103_x_at TNFAIP8L1\n", "4 11715104_s_at OTOP2\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data shape after mapping: (19521, 83)\n", "Gene expression data preview (first 5 genes, first 3 samples):\n", " GSM7136390 GSM7136391 GSM7136392\n", "Gene \n", "A1BG 12.349940 12.146990 12.794880\n", "A1CF 20.605627 20.181455 18.359397\n", "A2BP1 31.470516 29.878056 30.754822\n", "A2LD1 6.314692 6.396822 4.371634\n", "A2M 12.260090 12.144620 12.939880\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data shape after normalization: (19298, 83)\n", "Gene expression data after normalization (first 5 genes, first 3 samples):\n", " GSM7136390 GSM7136391 GSM7136392\n", "Gene \n", "A1BG 12.349940 12.146990 12.794880\n", "A1CF 20.605627 20.181455 18.359397\n", "A2M 12.260090 12.144620 12.939880\n", "A2ML1 6.258450 5.484635 6.210523\n", "A3GALT2 3.613935 3.541349 3.186719\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data saved to ../../output/preprocess/Liver_Cancer/gene_data/GSE228782.csv\n" ] } ], "source": [ "# 1. Identify columns for gene identifiers and gene symbols in the annotation data\n", "# The 'ID' column matches the probe identifiers seen in gene_data index\n", "# The 'Gene Symbol' column contains the corresponding gene symbols\n", "\n", "# 2. Extract gene mapping information using the get_gene_mapping function\n", "gene_mapping = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Gene Symbol')\n", "print(f\"Gene mapping shape: {gene_mapping.shape}\")\n", "print(\"Gene mapping preview:\")\n", "print(gene_mapping.head())\n", "\n", "# 3. Convert probe-level measurements to gene expression data using the apply_gene_mapping function\n", "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n", "print(f\"Gene expression data shape after mapping: {gene_data.shape}\")\n", "print(\"Gene expression data preview (first 5 genes, first 3 samples):\")\n", "print(gene_data.iloc[:5, :3])\n", "\n", "# Normalize gene symbols to handle synonyms\n", "gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"Gene expression data shape after normalization: {gene_data.shape}\")\n", "print(\"Gene expression data after normalization (first 5 genes, first 3 samples):\")\n", "print(gene_data.iloc[:5, :3])\n", "\n", "# Save gene expression data\n", "gene_data.to_csv(out_gene_data_file)\n", "print(f\"Gene expression data saved to {out_gene_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "4c05ffdc", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "97f39d60", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:30:37.668387Z", "iopub.status.busy": "2025-03-25T07:30:37.668266Z", "iopub.status.idle": "2025-03-25T07:30:49.096827Z", "shell.execute_reply": "2025-03-25T07:30:49.096266Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Normalizing gene symbols already completed in previous step\n", "\n", "Linking clinical and genetic data...\n", "Processed clinical data shape: (83, 1)\n", "Clinical data preview:\n", " Liver_Cancer\n", "GSM7136390 0.0\n", "GSM7136391 0.0\n", "GSM7136392 0.0\n", "GSM7136393 0.0\n", "GSM7136394 0.0\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape: (19298, 83)\n", "Common samples between clinical and gene data: 83\n", "Transposed gene data shape: (83, 19298)\n", "Linked data shape after merging: (83, 19299)\n", "Linked data preview (first 5 rows, first 5 columns):\n", " Liver_Cancer A1BG A1CF A2M A2ML1\n", "GSM7136390 0.0 12.34994 20.605627 12.26009 6.258450\n", "GSM7136391 0.0 12.14699 20.181455 12.14462 5.484635\n", "GSM7136392 0.0 12.79488 18.359397 12.93988 6.210523\n", "GSM7136393 0.0 12.74385 19.472532 12.81030 6.129710\n", "GSM7136394 0.0 12.70127 18.803324 12.75094 5.304150\n", "\n", "Handling missing values...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data shape after handling missing values: (83, 19299)\n", "\n", "Checking for bias in dataset features...\n", "For the feature 'Liver_Cancer', the least common label is '1.0' with 12 occurrences. This represents 14.46% of the dataset.\n", "The distribution of the feature 'Liver_Cancer' in this dataset is fine.\n", "\n", "\n", "Conducting final quality validation...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data saved to ../../output/preprocess/Liver_Cancer/GSE228782.csv\n" ] } ], "source": [ "# 1. Normalize gene symbols in the index - already done in step 6 (gene_data is already normalized)\n", "print(\"\\nNormalizing gene symbols already completed in previous step\")\n", "\n", "# 2. Link clinical and genetic data\n", "print(\"\\nLinking clinical and genetic data...\")\n", "\n", "# Read the matrix file to extract clinical data directly\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# Extracting clinical information again to get actual sample data\n", "# Get sample characteristic data from the matrix file\n", "background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']\n", "clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']\n", "_, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n", "\n", "# Get the unique values from each row to identify which row contains the disease information\n", "sample_chars_dict = get_unique_values_by_row(clinical_data)\n", "\n", "# Identify the row with disease information (row 2 based on previous steps)\n", "trait_row = 2 # From Step 2 where we identified trait row is at index 2\n", "\n", "# Create a proper clinical dataframe with trait information\n", "def convert_trait(value):\n", " \"\"\"\n", " Convert disease status to binary 0/1 for Liver Cancer.\n", " 1 for HCC (liver cancer), 0 for other conditions\n", " \"\"\"\n", " if not isinstance(value, str):\n", " return None\n", " \n", " # Extract value after colon\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # HCC is Hepatocellular Carcinoma (primary liver cancer)\n", " if value == 'HCC':\n", " return 1\n", " # CCC (Cholangiocarcinoma), CRC Met (Colorectal cancer metastases), and other are not primary liver cancer\n", " elif value in ['CCC', 'CRC Met', 'other']:\n", " return 0\n", " else:\n", " return None\n", "\n", "# Use the geo_select_clinical_features function to properly 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=None, # No age data available\n", " convert_age=None,\n", " gender_row=None, # No gender data available\n", " convert_gender=None\n", ")\n", "\n", "# Transpose to have samples as rows\n", "clinical_df_T = selected_clinical_df.T\n", "print(f\"Processed clinical data shape: {clinical_df_T.shape}\")\n", "print(\"Clinical data preview:\")\n", "print(clinical_df_T.head())\n", "\n", "# Read gene data\n", "gene_data = pd.read_csv(out_gene_data_file, index_col=0)\n", "print(f\"Gene data shape: {gene_data.shape}\")\n", "\n", "# Check if there are matching sample IDs between the clinical and gene data\n", "clinical_samples = set(clinical_df_T.index)\n", "gene_samples = set(gene_data.columns)\n", "common_samples = clinical_samples.intersection(gene_samples)\n", "print(f\"Common samples between clinical and gene data: {len(common_samples)}\")\n", "\n", "# If there are no common samples, we need to fix the sample IDs\n", "if len(common_samples) == 0:\n", " print(\"No common samples found. Checking if sample IDs need alignment...\")\n", " # Check if gene_data columns can be matched with clinical data rows by position\n", " # This is a fallback approach when IDs don't match directly\n", " if len(clinical_df_T) == len(gene_data.columns):\n", " print(\"Sample counts match. Assigning clinical sample IDs to gene data...\")\n", " gene_data.columns = clinical_df_T.index\n", " common_samples = set(clinical_df_T.index)\n", " print(f\"After realignment, common samples: {len(common_samples)}\")\n", "\n", "# Create the linked data - transpose gene data to have samples as rows\n", "gene_data_T = gene_data.T\n", "print(f\"Transposed gene data shape: {gene_data_T.shape}\")\n", "\n", "# Merge the clinical and gene data on the sample ID\n", "linked_data = pd.merge(clinical_df_T, gene_data_T, left_index=True, right_index=True, how='inner')\n", "print(f\"Linked data shape after merging: {linked_data.shape}\")\n", "print(\"Linked data preview (first 5 rows, first 5 columns):\")\n", "print(linked_data.iloc[:5, :5])\n", "\n", "if linked_data.shape[0] == 0:\n", " print(\"Error: No samples remaining after linking. Dataset cannot be used.\")\n", " is_usable = False\n", "else:\n", " # 3. Handle missing values\n", " print(\"\\nHandling missing values...\")\n", " linked_data_clean = handle_missing_values(linked_data, trait)\n", " print(f\"Linked data shape after handling missing values: {linked_data_clean.shape}\")\n", " \n", " # 4. Check for bias in the dataset\n", " print(\"\\nChecking for bias in dataset features...\")\n", " trait_biased, linked_data_clean = judge_and_remove_biased_features(linked_data_clean, trait)\n", " \n", " # 5. Conduct final quality validation and save metadata\n", " print(\"\\nConducting final quality validation...\")\n", " note = \"This dataset contains liver tissue gene expression data with samples categorized as HCC (hepatocellular carcinoma) or other conditions (CRC Met, CCC, other).\"\n", " is_gene_available = linked_data_clean.shape[1] > 1 # More than just the trait column\n", " is_trait_available = trait in linked_data_clean.columns\n", " is_usable = validate_and_save_cohort_info(\n", " is_final=True,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=is_gene_available,\n", " is_trait_available=is_trait_available,\n", " is_biased=trait_biased,\n", " df=linked_data_clean,\n", " note=note\n", " )\n", " \n", " # 6. 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", " linked_data_clean.to_csv(out_data_file)\n", " print(f\"Linked data saved to {out_data_file}\")\n", " else:\n", " print(\"Dataset deemed not usable for associative studies. 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 }