{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "4dab43dd", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:32:41.745402Z", "iopub.status.busy": "2025-03-25T07:32:41.745172Z", "iopub.status.idle": "2025-03-25T07:32:41.913780Z", "shell.execute_reply": "2025-03-25T07:32:41.913317Z" } }, "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 = \"GSE139602\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Liver_cirrhosis\"\n", "in_cohort_dir = \"../../input/GEO/Liver_cirrhosis/GSE139602\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Liver_cirrhosis/GSE139602.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Liver_cirrhosis/gene_data/GSE139602.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Liver_cirrhosis/clinical_data/GSE139602.csv\"\n", "json_path = \"../../output/preprocess/Liver_cirrhosis/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "f5029978", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "925baa59", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:32:41.915092Z", "iopub.status.busy": "2025-03-25T07:32:41.914936Z", "iopub.status.idle": "2025-03-25T07:32:42.065844Z", "shell.execute_reply": "2025-03-25T07:32:42.065479Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Molecular characterization of chronic liver disease dynamics: from liver fibrosis to acute-on-chronic liver failure\"\n", "!Series_summary\t\"BACKGROUND: The molecular mechanisms driving the progression from early chronic liver disease (eCLD) to cirrhosis and, finally, acute-on-chronic liver failure (ACLF) are largely unknown. Thus, the aim of this work is to develop a network-based approach to investigate molecular pathways driving progression from eCLD to ACLF. We created 9 liver-specific biological networks capturing key pathophysiological processes potentially related to CLD. We used these networks as framework to perform gene set enrichment analyses(GSEA) and create dynamic profiles of disease progression. RESULTS: Principal component analyses revealed that samples clustered according to the disease stage. GSEA analyses of the defined processes showed an up-regulation of inflammation, fibrosis and apoptosis networks throughout disease progression. Interestingly, we did not find significant gene expression differences between CC and DC, while ACLF showed acute expression changes in all the defined liver-related networks. The analyses of disease progression patterns identified ascending and descending expression profiles associated to ACLF onset. Functional analyses showed that ascending profiles were associated to inflammation, fibrosis, apoptosis, senescence and carcinogenesis networks, while descending profiles were mainly related to oxidative stress and genetic factors. We confirmed by qPCR the up-regulation of 4 genes of the ascending profile CXCL-6, KRT-18, SPINK-1, and ITGA2, and validated our findings on an independent patient’s cohort. CONCLUSION: ACLF is characterized by a specific hepatic gene expression pattern related to inflammation, fibrosis, apoptosis, senescence and carcinogenesis processes. Moreover, the observed profile is significantly different from that of compensated and decompensated cirrhosis, supporting thus the hypothesis that ACLF should be considered a distinct entity.\"\n", "!Series_overall_design\t\"Transcriptome analysis on liver biopsies from patients at different liver disease stages, including 5 fibrosis(eCLD), 8 compensated cirrhosis, 12 decompensated cirrhosis, 8 ACLF, and 6 control healthy livers was performed.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['disease state: Healthy', 'disease state: eCLD', 'disease state: Compensated Cirrhosis', 'disease state: Decompesated Cirrhosis', 'disease state: Acute-on-chronic liver failure']}\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": "28a694b6", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "4710b595", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:32:42.067345Z", "iopub.status.busy": "2025-03-25T07:32:42.067230Z", "iopub.status.idle": "2025-03-25T07:32:42.087384Z", "shell.execute_reply": "2025-03-25T07:32:42.086970Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Preview of selected clinical features:\n", "{0: [0.0]}\n" ] } ], "source": [ "# Step 1: Assess gene expression data availability\n", "# Given the background information, this dataset appears to contain gene expression data\n", "# from liver biopsies of patients at different liver disease stages.\n", "is_gene_available = True\n", "\n", "# Step 2: Variable availability and data type conversion\n", "# 2.1 Data Availability\n", "# For trait (cirrhosis), we can use the disease state information from key 0\n", "trait_row = 0\n", "age_row = None # Age information is not available\n", "gender_row = None # Gender information is not available\n", "\n", "# 2.2 Data Type Conversion\n", "def convert_trait(value):\n", " \"\"\"\n", " Convert disease state to binary: 1 for cirrhosis, 0 for non-cirrhosis.\n", " \"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract the value after colon if present\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Map disease states to binary values for liver cirrhosis\n", " if value == \"Healthy\" or value == \"eCLD\":\n", " return 0 # No cirrhosis\n", " elif \"Cirrhosis\" in value or \"ACLF\" in value or \"liver failure\" in value:\n", " return 1 # Has cirrhosis\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Placeholder function for age conversion.\"\"\"\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Placeholder function for gender conversion.\"\"\"\n", " return None\n", "\n", "# Step 3: Save metadata\n", "# Trait data is available since trait_row is not None\n", "is_trait_available = trait_row is not None\n", "validate_and_save_cohort_info(\n", " is_final=False,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=is_gene_available,\n", " is_trait_available=is_trait_available\n", ")\n", "\n", "# Step 4: Clinical Feature Extraction\n", "# Since trait_row is not None, we need to extract clinical features\n", "if is_trait_available:\n", " # Create properly formatted clinical data DataFrame\n", " sample_characteristics = {0: ['disease state: Healthy', 'disease state: eCLD', \n", " 'disease state: Compensated Cirrhosis', \n", " 'disease state: Decompesated Cirrhosis', \n", " 'disease state: Acute-on-chronic liver failure']}\n", " \n", " clinical_data = pd.DataFrame()\n", " for key, values in sample_characteristics.items():\n", " clinical_data[key] = values\n", " \n", " selected_clinical_df = geo_select_clinical_features(\n", " clinical_df=clinical_data,\n", " trait=trait,\n", " trait_row=trait_row,\n", " convert_trait=convert_trait,\n", " age_row=age_row,\n", " convert_age=convert_age,\n", " gender_row=gender_row,\n", " convert_gender=convert_gender\n", " )\n", "\n", " # Preview the extracted clinical data\n", " preview_result = preview_df(selected_clinical_df)\n", " print(\"Preview of selected clinical features:\")\n", " print(preview_result)\n", "\n", " # Save the clinical data to CSV\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " selected_clinical_df.to_csv(out_clinical_data_file, index=False)\n", "else:\n", " print(\"No trait data available. Skipping clinical feature extraction.\")\n" ] }, { "cell_type": "markdown", "id": "5e0dd2e8", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "e86a1350", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:32:42.088945Z", "iopub.status.busy": "2025-03-25T07:32:42.088831Z", "iopub.status.idle": "2025-03-25T07:32:42.304461Z", "shell.execute_reply": "2025-03-25T07:32:42.303905Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Matrix file found: ../../input/GEO/Liver_cirrhosis/GSE139602/GSE139602_series_matrix.txt.gz\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape: (49386, 39)\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": "dd956d62", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "ca47fe73", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:32:42.306335Z", "iopub.status.busy": "2025-03-25T07:32:42.306211Z", "iopub.status.idle": "2025-03-25T07:32:42.308575Z", "shell.execute_reply": "2025-03-25T07:32:42.308122Z" } }, "outputs": [], "source": [ "# Analyze the gene identifiers based on their format\n", "# The identifiers follow a pattern like \"11715100_at\", \"11715101_s_at\", etc.\n", "# These appear to be Affymetrix probe IDs rather than standard human gene symbols\n", "# Standard human gene symbols would be named like BRCA1, TP53, etc.\n", "# Therefore, these identifiers will need to be mapped to human gene symbols\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "12e64867", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "a37ce039", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:32:42.310411Z", "iopub.status.busy": "2025-03-25T07:32:42.310294Z", "iopub.status.idle": "2025-03-25T07:33:13.198728Z", "shell.execute_reply": "2025-03-25T07:33:13.198082Z" } }, "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", "Analyzing SPOT_ID.1 column for gene symbols:\n", "\n", "Gene data ID prefix: 11715100\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "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 'GeneChip Array' may contain gene-related information\n", "Sample values: ['Human Genome HG-U219 Array', 'Human Genome HG-U219 Array', 'Human Genome HG-U219 Array']\n", "Column 'Species Scientific Name' may contain gene-related information\n", "Sample values: ['Homo sapiens', 'Homo sapiens', 'Homo sapiens']\n", "Column 'Transcript ID(Array Design)' may contain gene-related information\n", "Sample values: ['g21264570', 'g21264570', 'g21264570']\n", "Column 'Target Description' may contain gene-related information\n", "Sample values: ['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']\n", "Column 'Archival UniGene Cluster' may contain gene-related information\n", "Sample values: ['---', '---', '---']\n", "Column 'UniGene ID' may contain gene-related information\n", "Sample values: ['Hs.247813', 'Hs.247813', 'Hs.247813']\n", "Column 'Gene Title' may contain gene-related information\n", "Sample values: ['histone cluster 1, H3g', 'histone cluster 1, H3g', 'histone cluster 1, H3g']\n", "Column 'Gene Symbol' may contain gene-related information\n", "Sample values: ['HIST1H3G', 'HIST1H3G', 'HIST1H3G']\n", "Column 'Unigene Cluster Type' may contain gene-related information\n", "Sample values: ['full length', 'full length', 'full length']\n", "Column 'Entrez Gene' may contain gene-related information\n", "Sample values: ['8355', '8355', '8355']\n", "Column 'RefSeq Transcript ID' may contain gene-related information\n", "Sample values: ['NM_003534', 'NM_003534', 'NM_003534']\n", "Column 'MGI Name' may contain gene-related information\n", "Sample values: ['---', '---', '---']\n", "Column 'RGD Name' may contain gene-related information\n", "Sample values: ['---', '---', '---']\n", "Column 'Gene Ontology Biological Process' may contain gene-related information\n", "Sample values: ['0006334 // nucleosome assembly // inferred from electronic annotation', '0006334 // nucleosome assembly // inferred from electronic annotation', '0006334 // nucleosome assembly // inferred from electronic annotation']\n", "Column 'Gene Ontology Cellular Component' may contain gene-related information\n", "Sample values: ['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']\n", "Column 'Gene Ontology Molecular Function' may contain gene-related information\n", "Sample values: ['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']\n", "Column 'Annotation Description' may contain gene-related information\n", "Sample values: ['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']\n", "Column 'Annotation Transcript Cluster' may contain gene-related information\n", "Sample values: ['NM_003534(11)', 'BC079835(11),NM_003534(11)', 'NM_003534(11)']\n", "Column 'Transcript Assignments' may contain gene-related information\n", "Sample values: ['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 // ---']\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": "4d18d73a", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "fe20ef2e", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:33:13.200692Z", "iopub.status.busy": "2025-03-25T07:33:13.200561Z", "iopub.status.idle": "2025-03-25T07:33:14.316764Z", "shell.execute_reply": "2025-03-25T07:33:14.316126Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Using ID for probe identifiers and Gene Symbol for gene symbols\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Created mapping dataframe with shape: (49384, 2)\n", "Sample of mapping data:\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ " 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", "Successfully converted probe-level to gene-level expression data\n", "Gene expression data shape: (19521, 39)\n", "First 5 gene symbols:\n", "Index(['A1BG', 'A1CF', 'A2BP1', 'A2LD1', 'A2M'], dtype='object', name='Gene')\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data saved to ../../output/preprocess/Liver_cirrhosis/gene_data/GSE139602.csv\n" ] } ], "source": [ "# 1. Identify the columns for probe IDs and gene symbols in the annotation data\n", "probe_col = 'ID' # Column containing probe identifiers (matching gene_data.index format)\n", "gene_col = 'Gene Symbol' # Column containing gene symbols\n", "\n", "print(f\"Using {probe_col} for probe identifiers and {gene_col} for gene symbols\")\n", "\n", "# 2. Extract the mapping dataframe with the get_gene_mapping function\n", "mapping_df = get_gene_mapping(gene_annotation, probe_col, gene_col)\n", "print(f\"Created mapping dataframe with shape: {mapping_df.shape}\")\n", "print(f\"Sample of mapping data:\")\n", "print(mapping_df.head())\n", "\n", "# 3. Apply gene mapping to convert probe-level expressions to gene-level expressions\n", "gene_data = apply_gene_mapping(gene_data, mapping_df)\n", "print(f\"Successfully converted probe-level to gene-level expression data\")\n", "print(f\"Gene expression data shape: {gene_data.shape}\")\n", "print(f\"First 5 gene symbols:\")\n", "print(gene_data.index[:5])\n", "\n", "# Save the gene expression data to a CSV file\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" ] }, { "cell_type": "markdown", "id": "584165f1", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "b5837a65", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:33:14.318590Z", "iopub.status.busy": "2025-03-25T07:33:14.318462Z", "iopub.status.idle": "2025-03-25T07:33:24.226492Z", "shell.execute_reply": "2025-03-25T07:33:24.226109Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape before normalization: (19521, 39)\n", "Gene data shape after normalization: (19298, 39)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene expression data saved to ../../output/preprocess/Liver_cirrhosis/gene_data/GSE139602.csv\n", "Original clinical data preview:\n", " !Sample_geo_accession GSM4144550 \\\n", "0 !Sample_characteristics_ch1 disease state: Healthy \n", "\n", " GSM4144551 GSM4144552 GSM4144553 \\\n", "0 disease state: Healthy disease state: Healthy disease state: Healthy \n", "\n", " GSM4144554 GSM4144555 GSM4144556 \\\n", "0 disease state: Healthy disease state: Healthy disease state: eCLD \n", "\n", " GSM4144557 GSM4144558 ... \\\n", "0 disease state: eCLD disease state: eCLD ... \n", "\n", " GSM4144579 \\\n", "0 disease state: Decompesated Cirrhosis \n", "\n", " GSM4144580 \\\n", "0 disease state: Decompesated Cirrhosis \n", "\n", " GSM4144581 \\\n", "0 disease state: Acute-on-chronic liver failure \n", "\n", " GSM4144582 \\\n", "0 disease state: Acute-on-chronic liver failure \n", "\n", " GSM4144583 \\\n", "0 disease state: Acute-on-chronic liver failure \n", "\n", " GSM4144584 \\\n", "0 disease state: Acute-on-chronic liver failure \n", "\n", " GSM4144585 \\\n", "0 disease state: Acute-on-chronic liver failure \n", "\n", " GSM4144586 \\\n", "0 disease state: Acute-on-chronic liver failure \n", "\n", " GSM4144587 \\\n", "0 disease state: Acute-on-chronic liver failure \n", "\n", " GSM4144588 \n", "0 disease state: Acute-on-chronic liver failure \n", "\n", "[1 rows x 40 columns]\n", "Selected clinical data shape: (1, 39)\n", "Clinical data preview:\n", " GSM4144550 GSM4144551 GSM4144552 GSM4144553 GSM4144554 \\\n", "Liver_cirrhosis 0.0 0.0 0.0 0.0 0.0 \n", "\n", " GSM4144555 GSM4144556 GSM4144557 GSM4144558 GSM4144559 \\\n", "Liver_cirrhosis 0.0 0.0 0.0 0.0 0.0 \n", "\n", " ... GSM4144579 GSM4144580 GSM4144581 GSM4144582 \\\n", "Liver_cirrhosis ... 1.0 1.0 1.0 1.0 \n", "\n", " GSM4144583 GSM4144584 GSM4144585 GSM4144586 GSM4144587 \\\n", "Liver_cirrhosis 1.0 1.0 1.0 1.0 1.0 \n", "\n", " GSM4144588 \n", "Liver_cirrhosis 1.0 \n", "\n", "[1 rows x 39 columns]\n", "Linked data shape before processing: (39, 19299)\n", "Linked data preview (first 5 rows, 5 columns):\n", " Liver_cirrhosis A1BG A1CF A2M A2ML1\n", "GSM4144550 0.0 12.144692 19.408778 12.380555 7.186744\n", "GSM4144551 0.0 12.405164 20.137335 12.763793 7.357133\n", "GSM4144552 0.0 11.583466 21.023954 12.196104 7.278308\n", "GSM4144553 0.0 11.790693 20.688341 13.217160 7.075635\n", "GSM4144554 0.0 11.935255 20.615757 13.293304 7.055198\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Data shape after handling missing values: (39, 19299)\n", "For the feature 'Liver_cirrhosis', the least common label is '0.0' with 11 occurrences. This represents 28.21% of the dataset.\n", "The distribution of the feature 'Liver_cirrhosis' in this dataset is fine.\n", "\n", "Data shape after removing biased features: (39, 19299)\n", "A new JSON file was created at: ../../output/preprocess/Liver_cirrhosis/cohort_info.json\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data saved to ../../output/preprocess/Liver_cirrhosis/GSE139602.csv\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", "# Load the actual clinical data from the matrix file that was previously obtained in Step 1\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "background_info, clinical_data = get_background_and_clinical_data(matrix_file)\n", "\n", "# Get preview of clinical data to understand its structure\n", "print(\"Original clinical data preview:\")\n", "print(clinical_data.head())\n", "\n", "# 2. If we have trait data available, proceed with linking\n", "if trait_row is not None:\n", " # Extract clinical features using the original clinical 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 and linked_data.shape[0] > 0:\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 or has no rows after missing value handling\")\n", "\n", " # 5. Validate and save cohort information\n", " note = \"\"\n", " if linked_data.empty or linked_data.shape[0] == 0:\n", " note = \"Dataset contains gene expression data related to liver fibrosis progression, but linking clinical and genetic data failed, possibly due to mismatched sample IDs.\"\n", " else:\n", " note = \"Dataset contains gene expression data for liver fibrosis progression, which is relevant to liver cirrhosis research.\"\n", " \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=note\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.\")\n", "else:\n", " # If no trait data available, validate 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 data without trait\n", " df=pd.DataFrame(), # Empty DataFrame\n", " note=\"Dataset contains gene expression data but lacks proper clinical trait information for liver cirrhosis analysis.\"\n", " )\n", " \n", " print(\"Dataset is not usable for liver cirrhosis analysis due to lack of clinical trait data. 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 }