{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "5bb7fab8", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:45:11.739007Z", "iopub.status.busy": "2025-03-25T06:45:11.738624Z", "iopub.status.idle": "2025-03-25T06:45:11.905128Z", "shell.execute_reply": "2025-03-25T06:45:11.904784Z" } }, "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 = \"GSE57691\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Atherosclerosis\"\n", "in_cohort_dir = \"../../input/GEO/Atherosclerosis/GSE57691\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Atherosclerosis/GSE57691.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Atherosclerosis/gene_data/GSE57691.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Atherosclerosis/clinical_data/GSE57691.csv\"\n", "json_path = \"../../output/preprocess/Atherosclerosis/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "9a6c0af4", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "ccbc5304", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:45:11.906513Z", "iopub.status.busy": "2025-03-25T06:45:11.906373Z", "iopub.status.idle": "2025-03-25T06:45:12.069320Z", "shell.execute_reply": "2025-03-25T06:45:12.068971Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Differential gene expression in human abdominal aortic aneurysm and atherosclerosis\"\n", "!Series_summary\t\"The aim of this study was to assess the relative gene expression in human AAA and AOD.\"\n", "!Series_overall_design\t\"Genome-wide expression analysis of abdominal aortic aneurysm (AAA) and aortic occlusive disease (AOD) specimens obtained from 20 patients with small AAA (mean maximum aortic diameter=54.3±2.3 mm), 29 patients with large AAA (mean maximum aortic diameter=68.4±14.3 mm), and 9 AOD patients (mean maximum aortic diameter=19.6±2.6 mm). Relative aortic gene expression was compared with that of 10 control aortic specimen of organ donors.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['disease state: small AAA', 'disease state: large AAA', 'disease state: AOD', 'disease state: control'], 1: ['subjects: patients with AAA undergoing open surgery to treat AAA', 'subjects: patients with AOD undergoing open surgery to treat chronic lower limb ischemia', 'subjects: heart-beating, brain-dead donors'], 2: ['tissue: full thickness aortic wall biopsies']}\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": "2b09505d", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "9b13c358", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:45:12.070601Z", "iopub.status.busy": "2025-03-25T06:45:12.070492Z", "iopub.status.idle": "2025-03-25T06:45:12.076206Z", "shell.execute_reply": "2025-03-25T06:45:12.075871Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Error processing clinical data: [Errno 2] No such file or directory: '../../input/GEO/Atherosclerosis/GSE57691/clinical_data.csv'\n", "Clinical data file not found. This may be expected if data was extracted differently.\n" ] } ], "source": [ "import pandas as pd\n", "import numpy as np\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, this dataset appears to contain gene expression data\n", "# Study title mentions \"Differential gene expression\"\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "# From the sample characteristics, we can see:\n", "# - disease state (related to Atherosclerosis) is at index 0\n", "# - Age is not available \n", "# - Gender is not available\n", "trait_row = 0\n", "age_row = None\n", "gender_row = None\n", "\n", "# 2.2 Data Type Conversion Functions\n", "def convert_trait(value):\n", " \"\"\"Convert trait value to binary format (0 for control, 1 for disease)\"\"\"\n", " if value is None or not isinstance(value, str):\n", " return None\n", " \n", " # Extract the value after the colon if it exists\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Convert values\n", " if 'control' in value.lower():\n", " return 0\n", " elif 'aod' in value.lower() or 'aaa' in value.lower():\n", " # Both AOD (Aortic Occlusive Disease) and AAA (Abdominal Aortic Aneurysm)\n", " # represent cases of atherosclerosis\n", " return 1\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age value to continuous format\"\"\"\n", " # Since age data is not available, this function is a placeholder\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender value to binary format (0 for female, 1 for male)\"\"\"\n", " # Since gender data is not available, this function is a placeholder\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Determine if trait data is available (based on whether trait_row is None)\n", "is_trait_available = trait_row is not None\n", "\n", "# Validate and save cohort info for initial filtering\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", "# Since trait_row is not None, we need to extract clinical features\n", "if trait_row is not None:\n", " # Assuming clinical_data has been loaded in a previous step\n", " try:\n", " # Ensure directory exists\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " \n", " # Read the clinical data from the input directory\n", " clinical_data = pd.read_csv(os.path.join(in_cohort_dir, \"clinical_data.csv\"))\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 dataframe\n", " preview = preview_df(selected_clinical_df)\n", " print(\"Preview of selected clinical features:\")\n", " print(preview)\n", " \n", " # Save the selected clinical data\n", " selected_clinical_df.to_csv(out_clinical_data_file, index=False)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n", " except Exception as e:\n", " print(f\"Error processing clinical data: {e}\")\n", " # If clinical data file doesn't exist, log the error\n", " if not os.path.exists(os.path.join(in_cohort_dir, \"clinical_data.csv\")):\n", " print(\"Clinical data file not found. This may be expected if data was extracted differently.\")\n" ] }, { "cell_type": "markdown", "id": "58c4fdd7", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "d83d8c76", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:45:12.077338Z", "iopub.status.busy": "2025-03-25T06:45:12.077233Z", "iopub.status.idle": "2025-03-25T06:45:12.366044Z", "shell.execute_reply": "2025-03-25T06:45:12.365664Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Matrix file found: ../../input/GEO/Atherosclerosis/GSE57691/GSE57691_series_matrix.txt.gz\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape: (39426, 68)\n", "First 20 gene/probe identifiers:\n", "Index(['ILMN_1343291', 'ILMN_1343295', 'ILMN_1651199', 'ILMN_1651209',\n", " 'ILMN_1651210', 'ILMN_1651221', 'ILMN_1651228', 'ILMN_1651229',\n", " 'ILMN_1651230', 'ILMN_1651232', 'ILMN_1651235', 'ILMN_1651236',\n", " 'ILMN_1651237', 'ILMN_1651238', 'ILMN_1651249', 'ILMN_1651253',\n", " 'ILMN_1651254', 'ILMN_1651259', 'ILMN_1651260', 'ILMN_1651262'],\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": "018c19c8", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "deeba8c9", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:45:12.367326Z", "iopub.status.busy": "2025-03-25T06:45:12.367210Z", "iopub.status.idle": "2025-03-25T06:45:12.369345Z", "shell.execute_reply": "2025-03-25T06:45:12.368956Z" } }, "outputs": [], "source": [ "# The identifiers seen in the gene data start with \"ILMN_\" which indicates these are Illumina microarray probe IDs\n", "# These are not human gene symbols and need to be mapped to gene symbols for proper analysis\n", "# ILMN_ identifiers are specific to Illumina BeadArray technology and require mapping to gene symbols\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "8b7e2294", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "614e15fc", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:45:12.370693Z", "iopub.status.busy": "2025-03-25T06:45:12.370591Z", "iopub.status.idle": "2025-03-25T06:45:18.851160Z", "shell.execute_reply": "2025-03-25T06:45:18.850776Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene annotation preview:\n", "Columns in gene annotation: ['ID', 'Species', 'Source', 'Search_Key', 'Transcript', 'ILMN_Gene', 'Source_Reference_ID', 'RefSeq_ID', 'Unigene_ID', 'Entrez_Gene_ID', 'GI', 'Accession', 'Symbol', 'Protein_Product', 'Probe_Id', 'Array_Address_Id', 'Probe_Type', 'Probe_Start', 'SEQUENCE', 'Chromosome', 'Probe_Chr_Orientation', 'Probe_Coordinates', 'Cytoband', 'Definition', 'Ontology_Component', 'Ontology_Process', 'Ontology_Function', 'Synonyms', 'Obsolete_Probe_Id', 'GB_ACC']\n", "{'ID': ['ILMN_1343048', 'ILMN_1343049', 'ILMN_1343050', 'ILMN_1343052', 'ILMN_1343059'], 'Species': [nan, nan, nan, nan, nan], 'Source': [nan, nan, nan, nan, nan], 'Search_Key': [nan, nan, nan, nan, nan], 'Transcript': [nan, nan, nan, nan, nan], 'ILMN_Gene': [nan, nan, nan, nan, nan], 'Source_Reference_ID': [nan, nan, nan, nan, nan], 'RefSeq_ID': [nan, nan, nan, nan, nan], 'Unigene_ID': [nan, nan, nan, nan, nan], 'Entrez_Gene_ID': [nan, nan, nan, nan, nan], 'GI': [nan, nan, nan, nan, nan], 'Accession': [nan, nan, nan, nan, nan], 'Symbol': ['phage_lambda_genome', 'phage_lambda_genome', 'phage_lambda_genome:low', 'phage_lambda_genome:low', 'thrB'], 'Protein_Product': [nan, nan, nan, nan, 'thrB'], 'Probe_Id': [nan, nan, nan, nan, nan], 'Array_Address_Id': [5090180.0, 6510136.0, 7560739.0, 1450438.0, 1240647.0], 'Probe_Type': [nan, nan, nan, nan, nan], 'Probe_Start': [nan, nan, nan, nan, nan], 'SEQUENCE': ['GAATAAAGAACAATCTGCTGATGATCCCTCCGTGGATCTGATTCGTGTAA', 'CCATGTGATACGAGGGCGCGTAGTTTGCATTATCGTTTTTATCGTTTCAA', 'CCGACAGATGTATGTAAGGCCAACGTGCTCAAATCTTCATACAGAAAGAT', 'TCTGTCACTGTCAGGAAAGTGGTAAAACTGCAACTCAATTACTGCAATGC', 'CTTGTGCCTGAGCTGTCAAAAGTAGAGCACGTCGCCGAGATGAAGGGCGC'], 'Chromosome': [nan, nan, nan, nan, nan], 'Probe_Chr_Orientation': [nan, nan, nan, nan, nan], 'Probe_Coordinates': [nan, nan, nan, nan, nan], 'Cytoband': [nan, nan, nan, nan, nan], 'Definition': [nan, nan, nan, nan, nan], 'Ontology_Component': [nan, nan, nan, nan, nan], 'Ontology_Process': [nan, nan, nan, nan, nan], 'Ontology_Function': [nan, nan, nan, nan, nan], 'Synonyms': [nan, nan, nan, nan, nan], 'Obsolete_Probe_Id': [nan, nan, nan, nan, nan], 'GB_ACC': [nan, nan, nan, nan, nan]}\n", "\n", "Exploring SOFT file more thoroughly for gene information:\n", "!Series_platform_id = GPL10558\n", "!Platform_title = Illumina HumanHT-12 V4.0 expression beadchip\n", "\n", "Found gene-related patterns:\n", "#Symbol = Gene symbol from the source database\n", "ID\tSpecies\tSource\tSearch_Key\tTranscript\tILMN_Gene\tSource_Reference_ID\tRefSeq_ID\tUnigene_ID\tEntrez_Gene_ID\tGI\tAccession\tSymbol\tProtein_Product\tProbe_Id\tArray_Address_Id\tProbe_Type\tProbe_Start\tSEQUENCE\tChromosome\tProbe_Chr_Orientation\tProbe_Coordinates\tCytoband\tDefinition\tOntology_Component\tOntology_Process\tOntology_Function\tSynonyms\tObsolete_Probe_Id\tGB_ACC\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: GPL10558\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": "ce33e64f", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "5c175739", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:45:18.852479Z", "iopub.status.busy": "2025-03-25T06:45:18.852361Z", "iopub.status.idle": "2025-03-25T06:45:19.819726Z", "shell.execute_reply": "2025-03-25T06:45:19.819382Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Determining which columns to use for gene mapping:\n", "Using 'ID' column as probe identifier and 'Symbol' column as gene symbol\n", "Gene mapping data shape: (44837, 2)\n", "Mapping data preview:\n", "{'ID': ['ILMN_1343048', 'ILMN_1343049', 'ILMN_1343050', 'ILMN_1343052', 'ILMN_1343059'], 'Gene': ['phage_lambda_genome', 'phage_lambda_genome', 'phage_lambda_genome:low', 'phage_lambda_genome:low', 'thrB']}\n", "Found 44837 probe-to-gene mappings\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data shape after mapping: (19295, 68)\n", "First 10 gene symbols after mapping:\n", "Index(['A1BG', 'A1CF', 'A26C3', 'A2BP1', 'A2M', 'A2ML1', 'A3GALT2', 'A4GALT',\n", " 'A4GNT', 'AAA1'],\n", " dtype='object', name='Gene')\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data saved to: ../../output/preprocess/Atherosclerosis/gene_data/GSE57691.csv\n" ] } ], "source": [ "# 1. Analyze the gene expression data and gene annotation data to identify matching columns\n", "print(\"\\nDetermining which columns to use for gene mapping:\")\n", "\n", "# Based on the gene expression data, we're using 'ID' as the identifier (ILMN_* format)\n", "# From the annotation data preview, 'Symbol' contains gene symbols\n", "prob_col = 'ID'\n", "gene_col = 'Symbol'\n", "\n", "print(f\"Using '{prob_col}' column as probe identifier and '{gene_col}' column as gene symbol\")\n", "\n", "# 2. Extract the gene mapping dataframe using the identified columns\n", "mapping_data = get_gene_mapping(gene_annotation, prob_col, gene_col)\n", "print(f\"Gene mapping data shape: {mapping_data.shape}\")\n", "print(\"Mapping data preview:\")\n", "print(preview_df(mapping_data, n=5))\n", "\n", "# Check if any mapping exists (non-empty mapping dataframe)\n", "if mapping_data.empty:\n", " print(\"Warning: Empty mapping data. No valid probe-to-gene mappings found.\")\n", "else:\n", " print(f\"Found {mapping_data.shape[0]} probe-to-gene mappings\")\n", "\n", "# 3. Apply gene mapping to convert probe-level measurements to gene expression data\n", "gene_data = apply_gene_mapping(gene_data, mapping_data)\n", "print(f\"Gene expression data shape after mapping: {gene_data.shape}\")\n", "print(\"First 10 gene symbols after mapping:\")\n", "print(gene_data.index[:10])\n", "\n", "# Save the gene data for future use\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": "1dbd9c6c", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "5777135d", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:45:19.821229Z", "iopub.status.busy": "2025-03-25T06:45:19.820932Z", "iopub.status.idle": "2025-03-25T06:45:30.290472Z", "shell.execute_reply": "2025-03-25T06:45:30.290102Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Normalizing gene symbols...\n", "Gene data shape after normalization: (18540, 68)\n", "First 10 normalized gene symbols:\n", "Index(['A1BG', 'A1CF', 'A2M', 'A2ML1', 'A3GALT2', 'A4GALT', 'A4GNT', 'AAA1',\n", " 'AAAS', 'AACS'],\n", " dtype='object', name='Gene')\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data saved to: ../../output/preprocess/Atherosclerosis/gene_data/GSE57691.csv\n", "\n", "Preparing clinical data...\n", "Clinical data preview:\n", "{'GSM1386783': [1.0], 'GSM1386784': [1.0], 'GSM1386785': [1.0], 'GSM1386786': [1.0], 'GSM1386787': [1.0], 'GSM1386788': [1.0], 'GSM1386789': [1.0], 'GSM1386790': [1.0], 'GSM1386791': [1.0], 'GSM1386792': [1.0], 'GSM1386793': [1.0], 'GSM1386794': [1.0], 'GSM1386795': [1.0], 'GSM1386796': [1.0], 'GSM1386797': [1.0], 'GSM1386798': [1.0], 'GSM1386799': [1.0], 'GSM1386800': [1.0], 'GSM1386801': [1.0], 'GSM1386802': [1.0], 'GSM1386803': [1.0], 'GSM1386804': [1.0], 'GSM1386805': [1.0], 'GSM1386806': [1.0], 'GSM1386807': [1.0], 'GSM1386808': [1.0], 'GSM1386809': [1.0], 'GSM1386810': [1.0], 'GSM1386811': [1.0], 'GSM1386812': [1.0], 'GSM1386813': [1.0], 'GSM1386814': [1.0], 'GSM1386815': [1.0], 'GSM1386816': [1.0], 'GSM1386817': [1.0], 'GSM1386818': [1.0], 'GSM1386819': [1.0], 'GSM1386820': [1.0], 'GSM1386821': [1.0], 'GSM1386822': [1.0], 'GSM1386823': [1.0], 'GSM1386824': [1.0], 'GSM1386825': [1.0], 'GSM1386826': [1.0], 'GSM1386827': [1.0], 'GSM1386828': [1.0], 'GSM1386829': [1.0], 'GSM1386830': [1.0], 'GSM1386831': [1.0], 'GSM1386832': [1.0], 'GSM1386833': [1.0], 'GSM1386834': [1.0], 'GSM1386835': [1.0], 'GSM1386836': [1.0], 'GSM1386837': [1.0], 'GSM1386838': [1.0], 'GSM1386839': [1.0], 'GSM1386840': [1.0], 'GSM1386841': [0.0], 'GSM1386842': [0.0], 'GSM1386843': [0.0], 'GSM1386844': [0.0], 'GSM1386845': [0.0], 'GSM1386846': [0.0], 'GSM1386847': [0.0], 'GSM1386848': [0.0], 'GSM1386849': [0.0], 'GSM1386850': [0.0]}\n", "Clinical data saved to: ../../output/preprocess/Atherosclerosis/clinical_data/GSE57691.csv\n", "\n", "Linking clinical and genetic data...\n", "Linked data shape: (68, 18541)\n", "Linked data preview (first 5 rows, 5 columns):\n", " Atherosclerosis A1BG A1CF A2M A2ML1\n", "GSM1386783 1.0 0.374157 1.259392 -3.756228 0.401806\n", "GSM1386784 1.0 -2.155580 -2.845751 -0.312673 -1.141962\n", "GSM1386785 1.0 0.827840 1.431236 -3.266001 0.617732\n", "GSM1386786 1.0 -2.380834 -2.802971 -0.462462 -0.616816\n", "GSM1386787 1.0 -2.238556 -3.576343 -0.863015 -0.969759\n", "\n", "Handling missing values...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data shape after handling missing values: (68, 18541)\n", "\n", "Checking for bias in dataset features...\n", "For the feature 'Atherosclerosis', the least common label is '0.0' with 10 occurrences. This represents 14.71% of the dataset.\n", "The distribution of the feature 'Atherosclerosis' in this dataset is fine.\n", "\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data saved to ../../output/preprocess/Atherosclerosis/GSE57691.csv\n" ] } ], "source": [ "# 1. Normalize gene symbols using NCBI database\n", "print(\"Normalizing gene symbols...\")\n", "gene_data = pd.read_csv(out_gene_data_file, index_col=0)\n", "gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"Gene data shape after normalization: {gene_data.shape}\")\n", "print(\"First 10 normalized gene symbols:\")\n", "print(gene_data.index[:10])\n", "\n", "# Save the normalized gene data\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 and prepare clinical data from the matrix file\n", "print(\"\\nPreparing clinical data...\")\n", "\n", "# Get the clinical data rows\n", "_, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\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", "# Process clinical data using the parameters defined in Step 2\n", "selected_clinical_df = geo_select_clinical_features(\n", " clinical_df=clinical_data,\n", " trait=trait,\n", " trait_row=0, # From Step 2: trait_row = 0\n", " convert_trait=convert_trait, # Function defined in Step 2\n", " age_row=None, # From Step 2: age_row = None\n", " convert_age=None,\n", " gender_row=None, # From Step 2: gender_row = None\n", " convert_gender=None\n", ")\n", "\n", "print(\"Clinical data preview:\")\n", "print(preview_df(selected_clinical_df))\n", "\n", "# Save the clinical data\n", "os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", "selected_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(selected_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 GSE57691 dataset contains gene expression data from patients with abdominal aortic aneurysm (AAA) and aortic occlusive disease (AOD) compared to control subjects. The dataset focuses on atherosclerosis-related vascular changes.\"\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 }