{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "e0e15fd5", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:45:31.180441Z", "iopub.status.busy": "2025-03-25T06:45:31.180255Z", "iopub.status.idle": "2025-03-25T06:45:31.348111Z", "shell.execute_reply": "2025-03-25T06:45:31.347669Z" } }, "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 = \"Atherosclerosis\"\n", "cohort = \"GSE83500\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Atherosclerosis\"\n", "in_cohort_dir = \"../../input/GEO/Atherosclerosis/GSE83500\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Atherosclerosis/GSE83500.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Atherosclerosis/gene_data/GSE83500.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Atherosclerosis/clinical_data/GSE83500.csv\"\n", "json_path = \"../../output/preprocess/Atherosclerosis/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "150e2721", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "c8d75f7c", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:45:31.349359Z", "iopub.status.busy": "2025-03-25T06:45:31.349217Z", "iopub.status.idle": "2025-03-25T06:45:31.499355Z", "shell.execute_reply": "2025-03-25T06:45:31.498891Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Expression data from aortic wall between myocardial infarction (MI) and non-MI group\"\n", "!Series_summary\t\"The aortic wall of patients with ischemic heart disease may have an indicative characteristic of mRNA predictive of future cardiovascular events.\"\n", "!Series_summary\t\"We used microarrays to detail the gene expression and identified distinct classes of up-regulated and down-regulated genes.\"\n", "!Series_overall_design\t\"Ascending aortic wall punch biopsies obtained as a standard part of coronary artery bypass surgery, will be used as a novel approach to study the vessel wall of patients with atherosclerosis. A total of 37 (17 MI, 20 Non-MI) frozen aortic tissues were embedded in TissueTek optimal cutting temperature (OCT) compound (TissueTek; Sakura Finetek USA). The embedded aortic tissues were trimmed and sectioned to a thickness of 10µm and placed on an RNase-free Polyethylene Naphthalate (PEN) membrane slide (Carl Zeiss; Germany). Haematoxylin and eosin staining (H&E) was also performed to establish the correct orientation of the embedded aortic tissue. Each slide containing frozen aortic sections was stained with Arcturus Histogene LCM Frozen Section Staining Kit (Applied Biosystems) according to the manufacturer’s protocol to enhance the visibility of VSMCs – elongated and spindle-shaped. LCM was performed immediately upon completion of staining using the LMPC technology in MicroBeam system (PALM microlaser, Carl Zeiss). The dissected VSMCs were scraped into a microcentrifuge tube containing 100µL of ice-cold TRI Reagent® (Molecular Research Centre, USA), with 19G sterile needles and freeze down in dry ice. Total RNA was isolated from VSMCs with Tri Reagent® (Molecular Research Centre) following manufacturer’s protocol and amplified with Ovation FFPE WTA System (NuGEN Technologies).\"\n", "Sample Characteristics Dictionary:\n", "{0: ['individual: MI patient', 'individual: non-MI patient'], 1: ['age: 69', 'age: 56', 'age: 53', 'age: 58', 'age: 70', 'age: 50', 'age: 61', 'age: 63', 'age: 65', 'age: 81', 'age: 68', 'age: 62', 'age: 64', 'age: 78', 'age: 52', 'age: 55', 'age: 48', 'age: 49', 'age: 54', 'age: 57'], 2: ['Sex: Male', 'Sex: Female'], 3: ['race: Malay', 'race: Chinese', 'race: Other', 'race: Indian'], 4: ['cad presentation: STEMI', 'cad presentation: UA', 'cad presentation: NSTEMI', 'cad presentation: STABLE'], 5: ['cell type: vascular smooth muscle cells (VSMCs)']}\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": "d054262e", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "518668ce", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:45:31.500523Z", "iopub.status.busy": "2025-03-25T06:45:31.500412Z", "iopub.status.idle": "2025-03-25T06:45:31.505432Z", "shell.execute_reply": "2025-03-25T06:45:31.505076Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene Expression Available: True\n", "Trait Available: True\n", "Trait Row: 0\n", "Age Row: 1\n", "Gender Row: 2\n" ] } ], "source": [ "import pandas as pd\n", "import os\n", "import json\n", "from typing import Optional, Callable, Dict, Any\n", "\n", "# 1. Gene Expression Data Availability\n", "# Based on the background information, the dataset contains gene expression data from aortic tissue\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "# For trait, row 0 has \"individual: MI patient\" vs \"individual: non-MI patient\"\n", "trait_row = 0\n", "\n", "# For age, row 1 has \"age: XX\" values\n", "age_row = 1\n", "\n", "# For gender, row 2 has \"Sex: Male\" vs \"Sex: Female\"\n", "gender_row = 2\n", "\n", "# 2.2 Data Type Conversion\n", "def convert_trait(value):\n", " \"\"\"Convert MI/non-MI to binary values (1/0)\"\"\"\n", " if value is None:\n", " return None\n", " value = value.lower()\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " if 'mi patient' in value:\n", " return 1 # MI patient\n", " elif 'non-mi patient' in value:\n", " return 0 # non-MI patient\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age string to numeric value\"\"\"\n", " if value is None:\n", " return None\n", " if ':' in value:\n", " try:\n", " return int(value.split(':', 1)[1].strip())\n", " except (ValueError, TypeError):\n", " return None\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender to binary (0 for female, 1 for male)\"\"\"\n", " if value is None:\n", " return None\n", " value = value.lower()\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " if 'female' in value:\n", " return 0\n", " elif 'male' in value:\n", " return 1\n", " return None\n", "\n", "# 3. Save Metadata - Initial filtering\n", "# Trait data is available if trait_row is not None\n", "is_trait_available = trait_row is not None\n", "\n", "# Validate and save cohort info (initial filtering)\n", "is_usable = 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", "# Since this is the analysis step and we don't yet have clinical_data.csv, \n", "# we're just identifying available variables and their conversion methods.\n", "# The actual clinical data loading and processing will happen in subsequent steps.\n", "print(f\"Gene Expression Available: {is_gene_available}\")\n", "print(f\"Trait Available: {is_trait_available}\")\n", "print(f\"Trait Row: {trait_row}\")\n", "print(f\"Age Row: {age_row}\")\n", "print(f\"Gender Row: {gender_row}\")\n" ] }, { "cell_type": "markdown", "id": "76b32b70", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "14aa5d86", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:45:31.506508Z", "iopub.status.busy": "2025-03-25T06:45:31.506395Z", "iopub.status.idle": "2025-03-25T06:45:31.727325Z", "shell.execute_reply": "2025-03-25T06:45:31.726755Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Matrix file found: ../../input/GEO/Atherosclerosis/GSE83500/GSE83500_series_matrix.txt.gz\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape: (49386, 37)\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": "c9e3dd89", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "978e9041", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:45:31.728843Z", "iopub.status.busy": "2025-03-25T06:45:31.728715Z", "iopub.status.idle": "2025-03-25T06:45:31.730856Z", "shell.execute_reply": "2025-03-25T06:45:31.730475Z" } }, "outputs": [], "source": [ "# The identifiers shown (11715100_at, etc.) are probe IDs from a microarray platform,\n", "# not standard human gene symbols. These will need to be mapped to gene symbols.\n", "# Affymetrix probe IDs typically follow this pattern with \"_at\" suffixes.\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "6b024bec", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "939ef100", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:45:31.732294Z", "iopub.status.busy": "2025-03-25T06:45:31.732185Z", "iopub.status.idle": "2025-03-25T06:45:37.573167Z", "shell.execute_reply": "2025-03-25T06:45:37.572517Z" } }, "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", "Exploring SOFT file more thoroughly for gene information:\n", "!Series_platform_id = GPL13667\n", "!Platform_title = [HG-U219] Affymetrix Human Genome U219 Array\n", "\n", "Found gene-related patterns:\n", "#Gene Symbol =\n", "ID\tGeneChip Array\tSpecies Scientific Name\tAnnotation Date\tSequence Type\tSequence Source\tTranscript ID(Array Design)\tTarget Description\tRepresentative Public ID\tArchival UniGene Cluster\tUniGene ID\tGenome Version\tAlignments\tGene Title\tGene Symbol\tChromosomal Location\tGB_LIST\tSPOT_ID\tUnigene Cluster Type\tEnsembl\tEntrez Gene\tSwissProt\tEC\tOMIM\tRefSeq Protein ID\tRefSeq Transcript ID\tFlyBase\tAGI\tWormBase\tMGI Name\tRGD Name\tSGD accession number\tGene Ontology Biological Process\tGene Ontology Cellular Component\tGene Ontology Molecular Function\tPathway\tInterPro\tTrans Membrane\tQTL\tAnnotation Description\tAnnotation Transcript Cluster\tTranscript Assignments\tAnnotation Notes\n", "\n", "Analyzing ENTREZ_GENE_ID column:\n", "\n", "Looking for alternative annotation approaches:\n", "- Checking for platform ID or accession number in SOFT file\n", "Found platform GEO accession: GPL13667\n", "\n", "Warning: No suitable mapping column found for gene symbols\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", "# Let's explore the SOFT file more thoroughly to find gene symbols\n", "print(\"\\nExploring SOFT file more thoroughly for gene information:\")\n", "gene_info_patterns = []\n", "entrez_to_symbol = {}\n", "\n", "with gzip.open(soft_file, 'rt') as f:\n", " for i, line in enumerate(f):\n", " if i < 1000: # Check header section for platform info\n", " if '!Series_platform_id' in line or '!Platform_title' in line:\n", " print(line.strip())\n", " \n", " # Look for gene-related columns and patterns in the file\n", " if 'GENE_SYMBOL' in line or 'gene_symbol' in line or 'Symbol' in line:\n", " gene_info_patterns.append(line.strip())\n", " \n", " # Extract a mapping using ENTREZ_GENE_ID if available\n", " if len(gene_info_patterns) < 2 and 'ENTREZ_GENE_ID' in line and '\\t' in line:\n", " parts = line.strip().split('\\t')\n", " if len(parts) >= 2:\n", " try:\n", " # Attempt to add to mapping - assuming ENTREZ_GENE_ID could help with lookup\n", " entrez_id = parts[1]\n", " probe_id = parts[0]\n", " if entrez_id.isdigit() and entrez_id != probe_id:\n", " entrez_to_symbol[probe_id] = entrez_id\n", " except:\n", " pass\n", " \n", " if i > 10000 and len(gene_info_patterns) > 0: # Limit search but ensure we found something\n", " break\n", "\n", "# Show some of the patterns found\n", "if gene_info_patterns:\n", " print(\"\\nFound gene-related patterns:\")\n", " for pattern in gene_info_patterns[:5]:\n", " print(pattern)\n", "else:\n", " print(\"\\nNo explicit gene info patterns found\")\n", "\n", "# Let's try to match the ENTREZ_GENE_ID to the probe IDs\n", "print(\"\\nAnalyzing ENTREZ_GENE_ID column:\")\n", "if 'ENTREZ_GENE_ID' in gene_annotation.columns:\n", " # Check if ENTREZ_GENE_ID contains actual Entrez IDs (different from probe IDs)\n", " gene_annotation['ENTREZ_GENE_ID'] = gene_annotation['ENTREZ_GENE_ID'].astype(str)\n", " different_ids = (gene_annotation['ENTREZ_GENE_ID'] != gene_annotation['ID']).sum()\n", " print(f\"Number of entries where ENTREZ_GENE_ID differs from ID: {different_ids}\")\n", " \n", " if different_ids > 0:\n", " print(\"Some ENTREZ_GENE_ID values differ from probe IDs - this could be useful for mapping\")\n", " # Show examples of differing values\n", " diff_examples = gene_annotation[gene_annotation['ENTREZ_GENE_ID'] != gene_annotation['ID']].head(5)\n", " print(diff_examples)\n", " else:\n", " print(\"ENTREZ_GENE_ID appears to be identical to probe ID - not useful for mapping\")\n", "\n", "# Search for additional annotation information in the dataset\n", "print(\"\\nLooking for alternative annotation approaches:\")\n", "print(\"- Checking for platform ID or accession number in SOFT file\")\n", "\n", "platform_id = None\n", "with gzip.open(soft_file, 'rt') as f:\n", " for i, line in enumerate(f):\n", " if '!Platform_geo_accession' in line:\n", " platform_id = line.split('=')[1].strip().strip('\"')\n", " print(f\"Found platform GEO accession: {platform_id}\")\n", " break\n", " if i > 200:\n", " break\n", "\n", "# If we don't find proper gene symbol mappings, prepare to use the ENTREZ_GENE_ID as is\n", "if 'ENTREZ_GENE_ID' in gene_annotation.columns:\n", " print(\"\\nPreparing provisional gene mapping using ENTREZ_GENE_ID:\")\n", " mapping_data = gene_annotation[['ID', 'ENTREZ_GENE_ID']].copy()\n", " mapping_data.rename(columns={'ENTREZ_GENE_ID': 'Gene'}, inplace=True)\n", " print(f\"Provisional mapping data shape: {mapping_data.shape}\")\n", " print(preview_df(mapping_data, n=5))\n", "else:\n", " print(\"\\nWarning: No suitable mapping column found for gene symbols\")\n" ] }, { "cell_type": "markdown", "id": "add40271", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "6dc09920", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:45:37.575005Z", "iopub.status.busy": "2025-03-25T06:45:37.574868Z", "iopub.status.idle": "2025-03-25T06:45:37.879301Z", "shell.execute_reply": "2025-03-25T06:45:37.878644Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene mapping dataframe shape: (49384, 2)\n", "\n", "Gene mapping sample:\n", "{'ID': ['11715100_at', '11715101_s_at', '11715102_x_at', '11715103_x_at', '11715104_s_at'], 'Gene': ['HIST1H3G', 'HIST1H3G', 'HIST1H3G', 'TNFAIP8L1', 'OTOP2']}\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene expression data shape after mapping: (19521, 37)\n", "\n", "First 10 genes after mapping:\n", "['A1BG', 'A1CF', 'A2BP1', 'A2LD1', 'A2M', 'A2ML1', 'A3GALT2', 'A4GALT', 'A4GNT', 'AAA1']\n", "\n", "Number of genes mapped from multiple probes: 12611\n", "Top 5 genes with the most probes:\n", "Gene\n", "--- 600\n", "NF1 21\n", "NFATC4 16\n", "FMNL1 16\n", "DMKN 16\n", "Name: count, dtype: int64\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene data shape after normalization: (19298, 37)\n" ] } ], "source": [ "# 1. Identify columns containing probe IDs and gene symbols in the gene annotation dataframe\n", "# Based on previous output, we can see:\n", "# - 'ID' column contains probe IDs (matching gene_data.index format like \"11715100_at\")\n", "# - 'Gene Symbol' column contains gene symbols (like \"HIST1H3G\", \"TNFAIP8L1\")\n", "\n", "# 2. Create gene mapping dataframe\n", "mapping_data = get_gene_mapping(gene_annotation, 'ID', 'Gene Symbol')\n", "print(f\"Gene mapping dataframe shape: {mapping_data.shape}\")\n", "print(\"\\nGene mapping sample:\")\n", "print(preview_df(mapping_data, n=5))\n", "\n", "# 3. Convert probe-level measurements to gene expression data\n", "gene_data = apply_gene_mapping(gene_data, mapping_data)\n", "print(f\"\\nGene expression data shape after mapping: {gene_data.shape}\")\n", "print(\"\\nFirst 10 genes after mapping:\")\n", "print(gene_data.index[:10].tolist())\n", "\n", "# Check if genes with multiple probes were properly aggregated\n", "gene_counts = mapping_data['Gene'].value_counts()\n", "multi_probe_genes = gene_counts[gene_counts > 1]\n", "print(f\"\\nNumber of genes mapped from multiple probes: {len(multi_probe_genes)}\")\n", "if len(multi_probe_genes) > 0:\n", " print(\"Top 5 genes with the most probes:\")\n", " print(multi_probe_genes.head())\n", "\n", "# Normalize gene symbols to ensure consistency (handle synonyms)\n", "gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"\\nGene data shape after normalization: {gene_data.shape}\")\n" ] }, { "cell_type": "markdown", "id": "ab4a1d51", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "7fe27370", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:45:37.881166Z", "iopub.status.busy": "2025-03-25T06:45:37.881021Z", "iopub.status.idle": "2025-03-25T06:45:44.966549Z", "shell.execute_reply": "2025-03-25T06:45:44.966024Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Saving normalized gene expression data...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data saved to: ../../output/preprocess/Atherosclerosis/gene_data/GSE83500.csv\n", "\n", "Extracting clinical data...\n", "Clinical data shape: (3, 37)\n", "Clinical data preview:\n", "{'GSM2204583': [1.0, 69.0, 1.0], 'GSM2204584': [1.0, 56.0, 1.0], 'GSM2204585': [1.0, 56.0, 1.0], 'GSM2204586': [1.0, 53.0, 1.0], 'GSM2204587': [1.0, 58.0, 1.0], 'GSM2204588': [1.0, 70.0, 1.0], 'GSM2204589': [1.0, 50.0, 1.0], 'GSM2204590': [1.0, 61.0, 0.0], 'GSM2204591': [1.0, 63.0, 1.0], 'GSM2204592': [1.0, 56.0, 1.0], 'GSM2204593': [1.0, 65.0, 1.0], 'GSM2204594': [1.0, 58.0, 1.0], 'GSM2204595': [1.0, 81.0, 0.0], 'GSM2204596': [1.0, 68.0, 0.0], 'GSM2204597': [1.0, 62.0, 1.0], 'GSM2204598': [1.0, 64.0, 1.0], 'GSM2204599': [1.0, 50.0, 1.0], 'GSM2204600': [1.0, 81.0, 0.0], 'GSM2204601': [1.0, 78.0, 1.0], 'GSM2204602': [1.0, 56.0, 1.0], 'GSM2204603': [1.0, 52.0, 0.0], 'GSM2204604': [1.0, 55.0, 1.0], 'GSM2204605': [1.0, 48.0, 1.0], 'GSM2204606': [1.0, 49.0, 1.0], 'GSM2204607': [1.0, 55.0, 1.0], 'GSM2204608': [1.0, 64.0, 1.0], 'GSM2204609': [1.0, 52.0, 1.0], 'GSM2204610': [1.0, 56.0, 1.0], 'GSM2204611': [1.0, 53.0, 1.0], 'GSM2204612': [1.0, 54.0, 1.0], 'GSM2204613': [1.0, 63.0, 1.0], 'GSM2204614': [1.0, 70.0, 1.0], 'GSM2204615': [1.0, 63.0, 1.0], 'GSM2204616': [1.0, 57.0, 1.0], 'GSM2204617': [1.0, 52.0, 1.0], 'GSM2204618': [1.0, 62.0, 1.0], 'GSM2204619': [1.0, 61.0, 1.0]}\n", "Clinical data saved to: ../../output/preprocess/Atherosclerosis/clinical_data/GSE83500.csv\n", "\n", "Linking clinical and genetic data...\n", "Linked data shape: (37, 19301)\n", "Linked data preview (first 5 rows, 5 columns):\n", " Atherosclerosis Age Gender A1BG A1CF\n", "GSM2204583 1.0 69.0 1.0 0.924468 3.804130\n", "GSM2204584 1.0 56.0 1.0 0.705995 4.137636\n", "GSM2204585 1.0 56.0 1.0 1.381072 3.624400\n", "GSM2204586 1.0 53.0 1.0 1.673025 3.577411\n", "GSM2204587 1.0 58.0 1.0 1.025280 2.922974\n", "\n", "Handling missing values...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data shape after handling missing values: (37, 19301)\n", "\n", "Checking for bias in dataset features...\n", "Quartiles for 'Atherosclerosis':\n", " 25%: 1.0\n", " 50% (Median): 1.0\n", " 75%: 1.0\n", "Min: 1.0\n", "Max: 1.0\n", "The distribution of the feature 'Atherosclerosis' in this dataset is severely biased.\n", "\n", "Quartiles for 'Age':\n", " 25%: 54.0\n", " 50% (Median): 58.0\n", " 75%: 64.0\n", "Min: 48.0\n", "Max: 81.0\n", "The distribution of the feature 'Age' in this dataset is fine.\n", "\n", "For the feature 'Gender', the least common label is '0.0' with 5 occurrences. This represents 13.51% of the dataset.\n", "The distribution of the feature 'Gender' in this dataset is fine.\n", "\n", "Dataset deemed not usable for associative studies. Linked data not saved.\n" ] } ], "source": [ "# 1. First save the normalized gene expression data from the previous step\n", "print(\"Saving normalized gene expression data...\")\n", "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", "gene_data.to_csv(out_gene_data_file)\n", "print(f\"Normalized gene data saved to: {out_gene_data_file}\")\n", "\n", "# 2. Extract the clinical data using the convert functions defined in step 2\n", "print(\"\\nExtracting clinical data...\")\n", "clinical_df = geo_select_clinical_features(\n", " clinical_data, # First parameter is the dataframe\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(\"Clinical data shape:\", clinical_df.shape)\n", "print(\"Clinical data preview:\")\n", "print(preview_df(clinical_df, n=5))\n", "\n", "# Save the clinical data\n", "os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", "clinical_df.to_csv(out_clinical_data_file)\n", "print(f\"Clinical data saved to: {out_clinical_data_file}\")\n", "\n", "# 3. Link clinical and genetic data\n", "print(\"\\nLinking clinical and genetic data...\")\n", "linked_data = geo_link_clinical_genetic_data(clinical_df, gene_data)\n", "print(f\"Linked data shape: {linked_data.shape}\")\n", "print(\"Linked data preview (first 5 rows, 5 columns):\")\n", "if linked_data.shape[0] > 0 and linked_data.shape[1] > 5:\n", " print(linked_data.iloc[:5, :5])\n", "else:\n", " print(linked_data)\n", "\n", "# 4. 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", "# 5. Check for bias in the dataset\n", "print(\"\\nChecking for bias in dataset features...\")\n", "is_biased, linked_data_clean = judge_and_remove_biased_features(linked_data_clean, trait)\n", "\n", "# 6. Conduct final quality validation\n", "note = \"This GSE83500 dataset contains gene expression data from aortic wall of patients with ischemic heart disease, comparing MI patients with non-MI patients. Clinical data includes age, gender, and MI status.\"\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_clean,\n", " note=note\n", ")\n", "\n", "# 7. Save the linked data if it's usable\n", "if is_usable:\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " linked_data_clean.to_csv(out_data_file, index=True)\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 }