{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "c9f5e849", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:06:59.430425Z", "iopub.status.busy": "2025-03-25T07:06:59.430317Z", "iopub.status.idle": "2025-03-25T07:06:59.596854Z", "shell.execute_reply": "2025-03-25T07:06:59.596488Z" } }, "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 = \"Cardiovascular_Disease\"\n", "cohort = \"GSE235307\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Cardiovascular_Disease\"\n", "in_cohort_dir = \"../../input/GEO/Cardiovascular_Disease/GSE235307\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Cardiovascular_Disease/GSE235307.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Cardiovascular_Disease/gene_data/GSE235307.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Cardiovascular_Disease/clinical_data/GSE235307.csv\"\n", "json_path = \"../../output/preprocess/Cardiovascular_Disease/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "8e4e4ab0", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "db301040", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:06:59.598296Z", "iopub.status.busy": "2025-03-25T07:06:59.598148Z", "iopub.status.idle": "2025-03-25T07:07:00.020157Z", "shell.execute_reply": "2025-03-25T07:07:00.019763Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Gene expression and atrial fibrillation prediction\"\n", "!Series_summary\t\"The aim of this study was to identify a blood gene expression profile that predicts atrial fibrillation in heart failure patients\"\n", "!Series_overall_design\t\"Cardiac blood samples were obtained from the coronary sinus during CRT-D (Cardiac Resynchronization Therapy - Defibrillator) placement in heart failure patients. Patients were followed during 1 year.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['tissue: Whole blood'], 1: ['gender: Male', 'gender: Female'], 2: ['age: 63', 'age: 60', 'age: 72', 'age: 66', 'age: 70', 'age: 64', 'age: 61', 'age: 44', 'age: 54', 'age: 50', 'age: 79', 'age: 51', 'age: 55', 'age: 67', 'age: 52', 'age: 73', 'age: 76', 'age: 43', 'age: 68', 'age: 78', 'age: 69', 'age: 57', 'age: 59', 'age: 53', 'age: 65', 'age: 56', 'age: 74', 'age: 38', 'age: 71', 'age: 37'], 3: ['cardiopathy: ischemic', 'cardiopathy: non ischemic', 'cardiopathy: mixed'], 4: ['cardiac rhythm at start of the study: Sinus rhythm'], 5: ['cardiac rhythm after 1 year follow-up: Sinus rhythm', 'cardiac rhythm after 1 year follow-up: Atrial fibrillation']}\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": "485069a5", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "73e6af5a", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:07:00.021587Z", "iopub.status.busy": "2025-03-25T07:07:00.021460Z", "iopub.status.idle": "2025-03-25T07:07:00.027523Z", "shell.execute_reply": "2025-03-25T07:07:00.027220Z" } }, "outputs": [], "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 dataset description, this appears to be gene expression data from blood samples\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "\n", "# For trait: The trait appears to be \"Atrial fibrillation\" which can be inferred from row 5\n", "# \"cardiac rhythm after 1 year follow-up: Sinus rhythm\" or \"cardiac rhythm after 1 year follow-up: Atrial fibrillation\"\n", "trait_row = 5\n", "\n", "# For age: Age data is available in row 2\n", "age_row = 2\n", "\n", "# For gender: Gender data is available in row 1\n", "gender_row = 1\n", "\n", "# 2.2 Data Type Conversion Functions\n", "\n", "def convert_trait(value):\n", " \"\"\"Convert atrial fibrillation status to binary (0: No AF, 1: AF).\"\"\"\n", " if pd.isna(value) or value is None:\n", " return None\n", " value = value.strip() if isinstance(value, str) else value\n", " if isinstance(value, str) and \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " if \"Atrial fibrillation\" in value:\n", " return 1 # Atrial fibrillation is present (positive case)\n", " elif \"Sinus rhythm\" in value:\n", " return 0 # Normal sinus rhythm (negative case)\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age to continuous numeric value.\"\"\"\n", " if pd.isna(value) or value is None:\n", " return None\n", " value = value.strip() if isinstance(value, str) else value\n", " if isinstance(value, str) and \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " try:\n", " return float(value)\n", " except (ValueError, TypeError):\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender to binary (0: Female, 1: Male).\"\"\"\n", " if pd.isna(value) or value is None:\n", " return None\n", " value = value.strip() if isinstance(value, str) else value\n", " if isinstance(value, str) and \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " if \"Male\" in value or value.lower() == \"male\":\n", " return 1\n", " elif \"Female\" in value or value.lower() == \"female\":\n", " return 0\n", " return None\n", "\n", "# 3. Save Metadata - Initial Filtering\n", "# Trait data availability is determined by whether trait_row is 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", "# 4. Clinical Feature Extraction\n", "if trait_row is not None:\n", " # Load clinical data\n", " clinical_df_path = os.path.join(in_cohort_dir, \"clinical_data.csv\")\n", " if os.path.exists(clinical_df_path):\n", " clinical_data = pd.read_csv(clinical_df_path)\n", " \n", " # Extract clinical features\n", " clinical_features_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 features\n", " preview = preview_df(clinical_features_df)\n", " print(\"Preview of clinical features:\")\n", " print(preview)\n", " \n", " # Create directory if it doesn't exist\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " \n", " # Save to CSV\n", " clinical_features_df.to_csv(out_clinical_data_file, index=False)\n", " print(f\"Clinical features saved to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "8366cd1d", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "9862983c", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:07:00.028687Z", "iopub.status.busy": "2025-03-25T07:07:00.028577Z", "iopub.status.idle": "2025-03-25T07:07:00.810364Z", "shell.execute_reply": "2025-03-25T07:07:00.809966Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Matrix file found: ../../input/GEO/Cardiovascular_Disease/GSE235307/GSE235307_series_matrix.txt.gz\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape: (58717, 119)\n", "First 20 gene/probe identifiers:\n", "Index(['4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16',\n", " '17', '18', '19', '20', '21', '22', '23'],\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": "08213599", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "48d98187", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:07:00.811773Z", "iopub.status.busy": "2025-03-25T07:07:00.811662Z", "iopub.status.idle": "2025-03-25T07:07:00.813568Z", "shell.execute_reply": "2025-03-25T07:07:00.813292Z" } }, "outputs": [], "source": [ "# Examine the gene identifiers\n", "# These appear to be numeric identifiers (4, 5, 6, etc.) which are not standard human gene symbols\n", "# Standard human gene symbols would be like BRCA1, TP53, etc.\n", "# Therefore, these identifiers need to be mapped to proper gene symbols\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "bd8aaa0c", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "26aa25a9", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:07:00.814754Z", "iopub.status.busy": "2025-03-25T07:07:00.814654Z", "iopub.status.idle": "2025-03-25T07:07:12.419016Z", "shell.execute_reply": "2025-03-25T07:07:12.418663Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene annotation preview:\n", "Columns in gene annotation: ['ID', 'COL', 'ROW', 'NAME', 'SPOT_ID', 'CONTROL_TYPE', 'REFSEQ', 'GB_ACC', 'LOCUSLINK_ID', 'GENE_SYMBOL', 'GENE_NAME', 'UNIGENE_ID', 'ENSEMBL_ID', 'ACCESSION_STRING', 'CHROMOSOMAL_LOCATION', 'CYTOBAND', 'DESCRIPTION', 'GO_ID', 'SEQUENCE']\n", "{'ID': ['1', '2', '3', '4', '5'], 'COL': ['192', '192', '192', '192', '192'], 'ROW': [328.0, 326.0, 324.0, 322.0, 320.0], 'NAME': ['GE_BrightCorner', 'DarkCorner', 'DarkCorner', 'A_23_P117082', 'A_33_P3246448'], 'SPOT_ID': ['CONTROL', 'CONTROL', 'CONTROL', 'A_23_P117082', 'A_33_P3246448'], 'CONTROL_TYPE': ['pos', 'pos', 'pos', 'FALSE', 'FALSE'], 'REFSEQ': [nan, nan, nan, 'NM_015987', 'NM_080671'], 'GB_ACC': [nan, nan, nan, 'NM_015987', 'NM_080671'], 'LOCUSLINK_ID': [nan, nan, nan, 50865.0, 23704.0], 'GENE_SYMBOL': [nan, nan, nan, 'HEBP1', 'KCNE4'], 'GENE_NAME': [nan, nan, nan, 'heme binding protein 1', 'potassium voltage-gated channel, Isk-related family, member 4'], 'UNIGENE_ID': [nan, nan, nan, 'Hs.642618', 'Hs.348522'], 'ENSEMBL_ID': [nan, nan, nan, 'ENST00000014930', 'ENST00000281830'], 'ACCESSION_STRING': [nan, nan, nan, 'ref|NM_015987|ens|ENST00000014930|gb|AF117615|gb|BC016277', 'ref|NM_080671|ens|ENST00000281830|tc|THC2655788'], 'CHROMOSOMAL_LOCATION': [nan, nan, nan, 'chr12:13127906-13127847', 'chr2:223920197-223920256'], 'CYTOBAND': [nan, nan, nan, 'hs|12p13.1', 'hs|2q36.1'], 'DESCRIPTION': [nan, nan, nan, 'Homo sapiens heme binding protein 1 (HEBP1), mRNA [NM_015987]', 'Homo sapiens potassium voltage-gated channel, Isk-related family, member 4 (KCNE4), mRNA [NM_080671]'], 'GO_ID': [nan, nan, nan, 'GO:0005488(binding)|GO:0005576(extracellular region)|GO:0005737(cytoplasm)|GO:0005739(mitochondrion)|GO:0005829(cytosol)|GO:0007623(circadian rhythm)|GO:0020037(heme binding)', 'GO:0005244(voltage-gated ion channel activity)|GO:0005249(voltage-gated potassium channel activity)|GO:0006811(ion transport)|GO:0006813(potassium ion transport)|GO:0016020(membrane)|GO:0016021(integral to membrane)|GO:0016324(apical plasma membrane)'], 'SEQUENCE': [nan, nan, nan, 'AAGGGGGAAAATGTGATTTGTGCCTGATCTTTCATCTGTGATTCTTATAAGAGCTTTGTC', 'GCAAGTCTCTCTGCACCTATTAAAAAGTGATGTATATACTTCCTTCTTATTCTGTTGAGT']}\n", "\n", "Searching for platform information in SOFT file:\n", "Platform ID not found in first 100 lines\n", "\n", "Searching for gene symbol information in SOFT file:\n", "Found references to gene symbols:\n", "#GENE_SYMBOL = Gene Symbol\n", "ID\tCOL\tROW\tNAME\tSPOT_ID\tCONTROL_TYPE\tREFSEQ\tGB_ACC\tLOCUSLINK_ID\tGENE_SYMBOL\tGENE_NAME\tUNIGENE_ID\tENSEMBL_ID\tACCESSION_STRING\tCHROMOSOMAL_LOCATION\tCYTOBAND\tDESCRIPTION\tGO_ID\tSEQUENCE\n", "8\t192\t314\tA_33_P3319925\tA_33_P3319925\tFALSE\tXM_001133269\tXM_001133269\t730249\tIRG1\timmunoresponsive 1 homolog (mouse)\tHs.160789\tENST00000449753\tens|ENST00000449753|ens|ENST00000377462|ref|XM_001133269|ref|XM_003403661\tchr13:77532009-77532068\ths|13q22.3\timmunoresponsive 1 homolog (mouse) [Source:HGNC Symbol;Acc:33904] [ENST00000449753]\tGO:0019543(propionate catabolic process)|GO:0032496(response to lipopolysaccharide)|GO:0047547(2-methylcitrate dehydratase activity)\tAGAAGACCTAGAAGACTGTTCTGTGTTAACTACACTTCTCAAAGGACCCTCTCCACCAGA\n", "21\t192\t288\tA_33_P3261373\tens|ENST00000319813|tc|NP511499\tFALSE\t\t\t\t\t\t\tENST00000319813\tens|ENST00000319813|tc|NP511499\tchr11:48387097-48387038\ths|11p11.2\tolfactory receptor, family 4, subfamily C, member 5 [Source:HGNC Symbol;Acc:14702] [ENST00000319813]\t\tGAAAAATGCCATGAAGCAGCTCTGGAGCCAAATAATCTGGGGTAACAATTTGTGTGATTA\n", "25\t192\t280\tA_24_P286898\tA_24_P286898\tFALSE\t\tAB074280\t5599\tMAPK8\tmitogen-activated protein kinase 8\tHs.522924\tENST00000374189\tens|ENST00000374189|ens|ENST00000374182|ens|ENST00000374179|ens|ENST00000374176\tchr10:49647005-49647064\ths|10q11.22\tmitogen-activated protein kinase 8 [Source:HGNC Symbol;Acc:6881] [ENST00000374189]\tGO:0000166(nucleotide binding)|GO:0001503(ossification)|GO:0002224(toll-like receptor signaling pathway)|GO:0002755(MyD88-dependent toll-like receptor signaling pathway)|GO:0002756(MyD88-independent toll-like receptor signaling pathway)|GO:0004674(protein serine/threonine kinase activity)|GO:0004705(JUN kinase activity)|GO:0004707(MAP kinase activity)|GO:0005515(protein binding)|GO:0005524(ATP binding)|GO:0005634(nucleus)|GO:0005654(nucleoplasm)|GO:0005737(cytoplasm)|GO:0005739(mitochondrion)|GO:0005829(cytosol)|GO:0006915(apoptosis)|GO:0006950(response to stress)|GO:0007254(JNK cascade)|GO:0007258(JUN phosphorylation)|GO:0008063(Toll signaling pathway)|GO:0008624(induction of apoptosis by extracellular signals)|GO:0008629(induction of apoptosis by intracellular signals)|GO:0008633(activation of pro-apoptotic gene products)|GO:0009411(response to UV)|GO:0018105(peptidyl-serine phosphorylation)|GO:0018107(peptidyl-threonine phosphorylation)|GO:0031063(regulation of histone deacetylation)|GO:0031558(induction of apoptosis in response to chemical stimulus)|GO:0032091(negative regulation of protein binding)|GO:0032880(regulation of protein localization)|GO:0034130(toll-like receptor 1 signaling pathway)|GO:0034134(toll-like receptor 2 signaling pathway)|GO:0034138(toll-like receptor 3 signaling pathway)|GO:0034142(toll-like receptor 4 signaling pathway)|GO:0035033(histone deacetylase regulator activity)|GO:0042826(histone deacetylase binding)|GO:0043066(negative regulation of apoptosis)|GO:0045087(innate immune response)|GO:0046686(response to cadmium ion)|GO:0048011(nerve growth factor receptor signaling pathway)|GO:0051090(regulation of sequence-specific DNA binding transcription factor activity)|GO:0051403(stress-activated MAPK cascade)|GO:0071260(cellular response to mechanical stimulus)|GO:0090045(positive regulation of deacetylase activity)|GO:2000017(positive regulation of determination of dorsal identity)\tTTTGAGAAGCTGTTAATCTTTTAGCTGAATAATGAAGTTAGACTGAATTACGTGTCTCCC\n", "\n", "Checking for additional annotation files in the directory:\n", "[]\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 look for platform information in the SOFT file to understand the annotation better\n", "print(\"\\nSearching for platform information in SOFT file:\")\n", "with gzip.open(soft_file, 'rt') as f:\n", " for i, line in enumerate(f):\n", " if '!Series_platform_id' in line:\n", " print(line.strip())\n", " break\n", " if i > 100: # Limit search to first 100 lines\n", " print(\"Platform ID not found in first 100 lines\")\n", " break\n", "\n", "# Check if the SOFT file includes any reference to gene symbols\n", "print(\"\\nSearching for gene symbol information in SOFT file:\")\n", "with gzip.open(soft_file, 'rt') as f:\n", " gene_symbol_lines = []\n", " for i, line in enumerate(f):\n", " if 'GENE_SYMBOL' in line or 'gene_symbol' in line.lower() or 'symbol' in line.lower():\n", " gene_symbol_lines.append(line.strip())\n", " if i > 1000 and len(gene_symbol_lines) > 0: # Limit search but ensure we found something\n", " break\n", " \n", " if gene_symbol_lines:\n", " print(\"Found references to gene symbols:\")\n", " for line in gene_symbol_lines[:5]: # Show just first 5 matches\n", " print(line)\n", " else:\n", " print(\"No explicit gene symbol references found in first 1000 lines\")\n", "\n", "# Look for alternative annotation files or references in the directory\n", "print(\"\\nChecking for additional annotation files in the directory:\")\n", "all_files = os.listdir(in_cohort_dir)\n", "print([f for f in all_files if 'annotation' in f.lower() or 'platform' in f.lower() or 'gpl' in f.lower()])\n" ] }, { "cell_type": "markdown", "id": "de7c8663", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "1d0891b7", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:07:12.420378Z", "iopub.status.busy": "2025-03-25T07:07:12.420244Z", "iopub.status.idle": "2025-03-25T07:07:14.574295Z", "shell.execute_reply": "2025-03-25T07:07:14.573914Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene mapping preview:\n", "{'ID': ['4', '5', '6', '7', '8'], 'Gene': ['HEBP1', 'KCNE4', 'BPIFA3', 'LOC100129869', 'IRG1']}\n", "Shape of gene mapping dataframe: (54295, 2)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene expression data after mapping:\n", "Shape of gene expression data: (20353, 119)\n", "First 10 gene symbols:\n", "['A1BG', 'A1BG-AS1', 'A1CF', 'A2LD1', 'A2M', 'A2ML1', 'A2MP1', 'A4GALT', 'A4GNT', 'AA06']\n", "\n", "Gene expression data after normalization:\n", "Shape of gene expression data after normalization: (19847, 119)\n", "First 10 normalized gene symbols:\n", "['A1BG', 'A1BG-AS1', 'A1CF', 'A2M', 'A2ML1', 'A2MP1', 'A4GALT', 'A4GNT', 'AA06', 'AAA1']\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene expression data saved to ../../output/preprocess/Cardiovascular_Disease/gene_data/GSE235307.csv\n" ] } ], "source": [ "# 1. Observe the gene identifier and gene symbol columns in the gene annotation\n", "# From the preview, we can see:\n", "# - The gene identifiers in gene_data are numeric IDs (like '4', '5', '6')\n", "# - In gene_annotation, the 'ID' column contains similar numeric identifiers\n", "# - The 'GENE_SYMBOL' column contains the human gene symbols like 'HEBP1', 'KCNE4'\n", "\n", "# 2. Extract the gene identifier and gene symbol columns\n", "gene_mapping_df = get_gene_mapping(\n", " annotation=gene_annotation,\n", " prob_col='ID', # The column with probe IDs matching gene_data index\n", " gene_col='GENE_SYMBOL' # The column with human gene symbols\n", ")\n", "\n", "print(\"Gene mapping preview:\")\n", "print(preview_df(gene_mapping_df, n=5))\n", "print(f\"Shape of gene mapping dataframe: {gene_mapping_df.shape}\")\n", "\n", "# 3. Apply gene mapping to convert from probe-level to gene-level expression\n", "gene_data = apply_gene_mapping(\n", " expression_df=gene_data,\n", " mapping_df=gene_mapping_df\n", ")\n", "\n", "print(\"\\nGene expression data after mapping:\")\n", "print(f\"Shape of gene expression data: {gene_data.shape}\")\n", "print(\"First 10 gene symbols:\")\n", "print(list(gene_data.index[:10]))\n", "\n", "# Apply gene symbol normalization to standardize symbols and aggregate duplicates\n", "gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(\"\\nGene expression data after normalization:\")\n", "print(f\"Shape of gene expression data after normalization: {gene_data.shape}\")\n", "print(\"First 10 normalized gene symbols:\")\n", "print(list(gene_data.index[:10]))\n", "\n", "# Create directory if it doesn't exist\n", "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", "\n", "# Save the gene expression data to the specified output file\n", "gene_data.to_csv(out_gene_data_file)\n", "print(f\"\\nGene expression data saved to {out_gene_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "c54021b0", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "fce3430b", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:07:14.575915Z", "iopub.status.busy": "2025-03-25T07:07:14.575794Z", "iopub.status.idle": "2025-03-25T07:07:28.528574Z", "shell.execute_reply": "2025-03-25T07:07:28.527965Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Clinical features shape: (3, 119)\n", "Clinical features preview:\n", "{'GSM7498589': [0.0, 63.0, 1.0], 'GSM7498590': [0.0, 60.0, 1.0], 'GSM7498591': [0.0, 60.0, 1.0], 'GSM7498592': [0.0, 72.0, 1.0], 'GSM7498593': [0.0, 63.0, 1.0], 'GSM7498594': [0.0, 66.0, 0.0], 'GSM7498595': [0.0, 70.0, 1.0], 'GSM7498596': [0.0, 64.0, 1.0], 'GSM7498597': [0.0, 63.0, 1.0], 'GSM7498598': [0.0, 61.0, 1.0], 'GSM7498599': [0.0, 70.0, 0.0], 'GSM7498600': [0.0, 64.0, 1.0], 'GSM7498601': [0.0, 63.0, 1.0], 'GSM7498602': [0.0, 44.0, 1.0], 'GSM7498603': [0.0, 54.0, 1.0], 'GSM7498604': [0.0, 44.0, 1.0], 'GSM7498605': [0.0, 50.0, 1.0], 'GSM7498606': [1.0, 79.0, 1.0], 'GSM7498607': [0.0, 63.0, 1.0], 'GSM7498608': [0.0, 63.0, 0.0], 'GSM7498609': [1.0, 64.0, 1.0], 'GSM7498610': [0.0, 60.0, 1.0], 'GSM7498611': [0.0, 51.0, 1.0], 'GSM7498612': [0.0, 55.0, 1.0], 'GSM7498613': [0.0, 55.0, 1.0], 'GSM7498614': [1.0, 67.0, 1.0], 'GSM7498615': [0.0, 52.0, 1.0], 'GSM7498616': [0.0, 70.0, 0.0], 'GSM7498617': [0.0, 54.0, 1.0], 'GSM7498618': [0.0, 54.0, 1.0], 'GSM7498619': [0.0, 73.0, 1.0], 'GSM7498620': [0.0, 54.0, 0.0], 'GSM7498621': [0.0, 76.0, 1.0], 'GSM7498622': [0.0, 76.0, 1.0], 'GSM7498623': [0.0, 43.0, 0.0], 'GSM7498624': [0.0, 64.0, 1.0], 'GSM7498625': [0.0, 64.0, 1.0], 'GSM7498626': [0.0, 68.0, 0.0], 'GSM7498627': [0.0, 43.0, 1.0], 'GSM7498628': [1.0, 54.0, 1.0], 'GSM7498629': [0.0, 72.0, 0.0], 'GSM7498630': [0.0, 51.0, 1.0], 'GSM7498631': [0.0, 68.0, 0.0], 'GSM7498632': [0.0, 50.0, 0.0], 'GSM7498633': [0.0, 78.0, 1.0], 'GSM7498634': [1.0, 69.0, 1.0], 'GSM7498635': [0.0, 64.0, 0.0], 'GSM7498636': [0.0, 54.0, 1.0], 'GSM7498637': [0.0, 54.0, 1.0], 'GSM7498638': [0.0, 57.0, 1.0], 'GSM7498639': [0.0, 55.0, 0.0], 'GSM7498640': [0.0, 60.0, 1.0], 'GSM7498641': [0.0, 59.0, 1.0], 'GSM7498642': [0.0, 54.0, 1.0], 'GSM7498643': [0.0, 54.0, 1.0], 'GSM7498644': [0.0, 54.0, 1.0], 'GSM7498645': [0.0, 54.0, 1.0], 'GSM7498646': [0.0, 53.0, 1.0], 'GSM7498647': [0.0, 52.0, 0.0], 'GSM7498648': [0.0, 68.0, 1.0], 'GSM7498649': [0.0, 72.0, 0.0], 'GSM7498650': [0.0, 70.0, 1.0], 'GSM7498651': [0.0, 65.0, 1.0], 'GSM7498652': [0.0, 64.0, 1.0], 'GSM7498653': [0.0, 56.0, 0.0], 'GSM7498654': [0.0, 56.0, 0.0], 'GSM7498655': [0.0, 63.0, 1.0], 'GSM7498656': [0.0, 57.0, 1.0], 'GSM7498657': [0.0, 63.0, 1.0], 'GSM7498658': [0.0, 68.0, 1.0], 'GSM7498659': [0.0, 66.0, 0.0], 'GSM7498660': [0.0, 74.0, 0.0], 'GSM7498661': [0.0, 38.0, 1.0], 'GSM7498662': [0.0, 56.0, 1.0], 'GSM7498663': [0.0, 57.0, 1.0], 'GSM7498664': [0.0, 71.0, 0.0], 'GSM7498665': [1.0, 78.0, 0.0], 'GSM7498666': [0.0, 51.0, 1.0], 'GSM7498667': [0.0, 50.0, 1.0], 'GSM7498668': [0.0, 37.0, 1.0], 'GSM7498669': [0.0, 37.0, 1.0], 'GSM7498670': [0.0, 70.0, 0.0], 'GSM7498671': [0.0, 72.0, 0.0], 'GSM7498672': [0.0, 73.0, 1.0], 'GSM7498673': [0.0, 69.0, 0.0], 'GSM7498674': [0.0, 69.0, 0.0], 'GSM7498675': [1.0, 63.0, 1.0], 'GSM7498676': [0.0, 62.0, 0.0], 'GSM7498677': [0.0, 59.0, 0.0], 'GSM7498678': [0.0, 67.0, 1.0], 'GSM7498679': [0.0, 76.0, 1.0], 'GSM7498680': [0.0, 63.0, 1.0], 'GSM7498681': [0.0, 55.0, 1.0], 'GSM7498682': [0.0, 57.0, 1.0], 'GSM7498683': [0.0, 53.0, 1.0], 'GSM7498684': [0.0, 59.0, 1.0], 'GSM7498685': [1.0, 77.0, 1.0], 'GSM7498686': [0.0, 54.0, 1.0], 'GSM7498687': [1.0, 64.0, 1.0], 'GSM7498688': [0.0, 75.0, 0.0], 'GSM7498689': [0.0, 75.0, 0.0], 'GSM7498690': [0.0, 72.0, 0.0], 'GSM7498691': [0.0, 58.0, 0.0], 'GSM7498692': [0.0, 75.0, 1.0], 'GSM7498693': [0.0, 78.0, 1.0], 'GSM7498694': [0.0, 58.0, 1.0], 'GSM7498695': [0.0, 64.0, 1.0], 'GSM7498696': [0.0, 63.0, 1.0], 'GSM7498697': [0.0, 61.0, 1.0], 'GSM7498698': [0.0, 60.0, 1.0], 'GSM7498699': [0.0, 59.0, 0.0], 'GSM7498700': [0.0, 68.0, 1.0], 'GSM7498701': [0.0, 77.0, 1.0], 'GSM7498702': [1.0, 57.0, 1.0], 'GSM7498703': [0.0, 62.0, 0.0], 'GSM7498704': [1.0, 66.0, 1.0], 'GSM7498705': [1.0, 57.0, 1.0], 'GSM7498706': [1.0, 65.0, 1.0], 'GSM7498707': [0.0, 59.0, 1.0]}\n", "Clinical data saved to ../../output/preprocess/Cardiovascular_Disease/clinical_data/GSE235307.csv\n", "Linked data shape: (119, 19850)\n", "Linked data preview (first 5 rows, 5 columns):\n", " Cardiovascular_Disease Age Gender A1BG A1BG-AS1\n", "GSM7498589 0.0 63.0 1.0 1215.921532 167.933502\n", "GSM7498590 0.0 60.0 1.0 1042.240181 156.514231\n", "GSM7498591 0.0 60.0 1.0 860.505266 153.778492\n", "GSM7498592 0.0 72.0 1.0 1016.786080 164.688762\n", "GSM7498593 0.0 63.0 1.0 930.371907 153.624856\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data shape after handling missing values: (119, 19850)\n", "For the feature 'Cardiovascular_Disease', the least common label is '1.0' with 13 occurrences. This represents 10.92% of the dataset.\n", "The distribution of the feature 'Cardiovascular_Disease' in this dataset is fine.\n", "\n", "Quartiles for 'Age':\n", " 25%: 55.0\n", " 50% (Median): 63.0\n", " 75%: 68.0\n", "Min: 37.0\n", "Max: 79.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 32 occurrences. This represents 26.89% of the dataset.\n", "The distribution of the feature 'Gender' in this dataset is fine.\n", "\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data saved to ../../output/preprocess/Cardiovascular_Disease/GSE235307.csv\n" ] } ], "source": [ "# 1. Normalize gene symbols \n", "# (Note: We already normalized in step 6, but let's explicitly ensure it's done properly)\n", "\n", "# 2. Load the clinical data and extract features using the correct trait_row and conversion functions from Step 2\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", "# Define correct conversion functions matching the ones in Step 2\n", "def convert_trait(value):\n", " \"\"\"Convert atrial fibrillation status to binary (0: No AF, 1: AF).\"\"\"\n", " if pd.isna(value) or value is None:\n", " return None\n", " value = value.strip() if isinstance(value, str) else value\n", " if isinstance(value, str) and \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " if \"Atrial fibrillation\" in value:\n", " return 1 # Atrial fibrillation is present (positive case)\n", " elif \"Sinus rhythm\" in value:\n", " return 0 # Normal sinus rhythm (negative case)\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age to continuous numeric value.\"\"\"\n", " if pd.isna(value) or value is None:\n", " return None\n", " value = value.strip() if isinstance(value, str) else value\n", " if isinstance(value, str) and \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " try:\n", " return float(value)\n", " except (ValueError, TypeError):\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender to binary (0: Female, 1: Male).\"\"\"\n", " if pd.isna(value) or value is None:\n", " return None\n", " value = value.strip() if isinstance(value, str) else value\n", " if isinstance(value, str) and \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " if \"Male\" in value or value.lower() == \"male\":\n", " return 1\n", " elif \"Female\" in value or value.lower() == \"female\":\n", " return 0\n", " return None\n", "\n", "# Extract clinical features using the correct row indices from Step 2\n", "clinical_features = geo_select_clinical_features(\n", " clinical_df=clinical_data, \n", " trait=trait, \n", " trait_row=5, # Correctly using cardiac rhythm row as identified in Step 2\n", " convert_trait=convert_trait,\n", " age_row=2, # Age information from row 2\n", " convert_age=convert_age,\n", " gender_row=1, # Gender information from row 1\n", " convert_gender=convert_gender\n", ")\n", "\n", "print(f\"Clinical features shape: {clinical_features.shape}\")\n", "print(\"Clinical features preview:\")\n", "print(preview_df(clinical_features))\n", "\n", "# Save the clinical data\n", "os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", "clinical_features.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", "linked_data = geo_link_clinical_genetic_data(clinical_features, gene_data)\n", "print(f\"Linked data shape: {linked_data.shape}\")\n", "print(\"Linked data preview (first 5 rows, 5 columns):\")\n", "print(linked_data.iloc[:5, :5])\n", "\n", "# 4. Handle 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", "is_biased, linked_data_clean = judge_and_remove_biased_features(linked_data_clean, trait)\n", "\n", "# 6. Conduct final quality validation\n", "note = \"Dataset contains gene expression data from cardiac blood samples of heart failure patients, with atrial fibrillation status tracked over 1 year.\"\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 }