{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "8094614c", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:45:00.675227Z", "iopub.status.busy": "2025-03-25T06:45:00.675047Z", "iopub.status.idle": "2025-03-25T06:45:00.842571Z", "shell.execute_reply": "2025-03-25T06:45:00.842110Z" } }, "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 = \"GSE154851\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Atherosclerosis\"\n", "in_cohort_dir = \"../../input/GEO/Atherosclerosis/GSE154851\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Atherosclerosis/GSE154851.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Atherosclerosis/gene_data/GSE154851.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Atherosclerosis/clinical_data/GSE154851.csv\"\n", "json_path = \"../../output/preprocess/Atherosclerosis/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "6ea0f3c1", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "79c266d3", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:45:00.843907Z", "iopub.status.busy": "2025-03-25T06:45:00.843757Z", "iopub.status.idle": "2025-03-25T06:45:01.080760Z", "shell.execute_reply": "2025-03-25T06:45:01.080249Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Investigation Of Genes Associated With Atherosclerosis In Patients With Systemic Lupus Erythematosus\"\n", "!Series_summary\t\"Systemic lupus erythematosus (SLE) is a chronic, autoimmune disease affecting multiple heterogeneous organs and systems. SLE is associated with increased risk of atherosclerosis and increased cardiovascular complications. In this study, we specifically aimed to identify patients with SLE who are genetically at risk for developing atherosclerosis. Sureprint G3 Human Gene Expression 8x60K Microarray kit (Agilent technologies, Santa Clara, CA, USA) was used in our study. Genes showing differences in expression between the groups were identified by using GeneSpring GX 10.0 program. A total of 155 genes showing expression level difference were detected between SLE patients and healthy controls. In molecular network analysis.\"\n", "!Series_overall_design\t\"38 patients with systemic lupus erythematosus (36 females, 2 males) and 32 healthy controls (32 females) were included in the study. Sureprint G3 Human Gene Expression 8x60K Microarray kit (Agilent technologies, Santa Clara, CA, USA) was used in our study.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['tissue: whole blood'], 1: ['gender: female', 'gender: male'], 2: ['age: 18y', 'age: 37y', 'age: 59y', 'age: 36y', 'age: 56y', 'age: 22y', 'age: 53y', 'age: 41y', 'age: 33y', 'age: 52y', 'age: 42y', 'age: 28y', 'age: 45y', 'age: 25y', 'age: 34y', 'age: 40y', 'age: 44y', 'age: 39y', 'age: 51y', 'age: 21y', 'age: 23y', 'age: 32y', 'age: 71y', 'age: 26y', 'age: 31y', 'age: 24y', 'age: 30y', 'age: 47y', 'age: 35y', 'age: 19y']}\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": "2a9fbd18", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "ef4dbf87", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:45:01.082450Z", "iopub.status.busy": "2025-03-25T06:45:01.082336Z", "iopub.status.idle": "2025-03-25T06:45:01.087583Z", "shell.execute_reply": "2025-03-25T06:45:01.087136Z" } }, "outputs": [], "source": [ "\"\"\"\n", "Analysis:\n", "- This dataset appears to study atherosclerosis in SLE patients vs healthy controls\n", "- It uses gene expression microarray data, which is suitable for our analysis\n", "- Sample characteristics include:\n", " - Gender (Key 1): mostly female with some male participants\n", " - Age (Key 2): ranges from 18 to 71 years\n", " - Disease status: Not explicitly in sample characteristics, but from the background\n", " information we can infer SLE status, which is relevant to the trait (atherosclerosis)\n", "\"\"\"\n", "\n", "# 1. Gene Expression Data Availability\n", "# This dataset uses \"Sureprint G3 Human Gene Expression 8x60K Microarray kit\"\n", "is_gene_available = True\n", "\n", "# 2.1 Data Availability\n", "# From the background, we know SLE patients may have atherosclerosis risk\n", "# While atherosclerosis itself is not explicitly coded, we can use the SLE status as a proxy\n", "# (atherosclerosis is a complication of SLE according to the background)\n", "trait_row = None # No explicit atherosclerosis data\n", "age_row = 2 # Age information is available at key 2\n", "gender_row = 1 # Gender information is available at key 1\n", "\n", "# 2.2 Data Type Conversion Functions\n", "def convert_trait(value):\n", " # No direct atherosclerosis data\n", " return None\n", "\n", "def convert_age(value):\n", " # Extract numerical age from string like \"age: 18y\"\n", " try:\n", " if isinstance(value, str) and 'age:' in value:\n", " # Extract the number from strings like \"age: 18y\"\n", " age_str = value.split(':')[1].strip()\n", " return int(age_str.replace('y', ''))\n", " return None\n", " except:\n", " return None\n", "\n", "def convert_gender(value):\n", " # Convert gender values to binary (0=female, 1=male)\n", " try:\n", " if isinstance(value, str) and 'gender:' in value:\n", " gender = value.split(':')[1].strip().lower()\n", " if gender == 'female':\n", " return 0\n", " elif gender == 'male':\n", " return 1\n", " return None\n", " except:\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Initial filtering to check if dataset is usable\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", "# Since trait_row is None, we skip this substep\n", "# However, we can still extract age and gender information\n", "if trait_row is not None:\n", " # This block won't execute but is kept for completeness\n", " 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(clinical_df)\n", " print(\"Clinical Data Preview:\")\n", " print(preview)\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, index=False)\n" ] }, { "cell_type": "markdown", "id": "adb00c7a", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "4c9014c6", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:45:01.089198Z", "iopub.status.busy": "2025-03-25T06:45:01.089077Z", "iopub.status.idle": "2025-03-25T06:45:01.502620Z", "shell.execute_reply": "2025-03-25T06:45:01.502085Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Matrix file found: ../../input/GEO/Atherosclerosis/GSE154851/GSE154851_series_matrix.txt.gz\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape: (62976, 70)\n", "First 20 gene/probe identifiers:\n", "Index(['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13',\n", " '14', '15', '16', '17', '18', '19', '20'],\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": "6975e622", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "29b341a1", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:45:01.504400Z", "iopub.status.busy": "2025-03-25T06:45:01.504269Z", "iopub.status.idle": "2025-03-25T06:45:01.506603Z", "shell.execute_reply": "2025-03-25T06:45:01.506159Z" } }, "outputs": [], "source": [ "# The gene identifiers shown are numeric ('1', '2', '3', etc.) which are not human gene symbols.\n", "# These are likely probe IDs or internal identifiers that need to be mapped to gene symbols.\n", "# For proper biological interpretation, we need to map these to standard gene symbols.\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "ca2bbe2f", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "17fcf2a6", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:45:01.508480Z", "iopub.status.busy": "2025-03-25T06:45:01.508329Z", "iopub.status.idle": "2025-03-25T06:45:08.059269Z", "shell.execute_reply": "2025-03-25T06:45:08.058605Z" } }, "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", "Exploring SOFT file more thoroughly for gene information:\n", "!Series_platform_id = GPL16699\n", "!Platform_title = Agilent-039494 SurePrint G3 Human GE v2 8x60K Microarray 039381 (Feature Number version)\n", "\n", "Found gene-related patterns:\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", "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: GPL16699\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": "ac168a31", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "a1463f96", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:45:08.061222Z", "iopub.status.busy": "2025-03-25T06:45:08.061024Z", "iopub.status.idle": "2025-03-25T06:45:09.438931Z", "shell.execute_reply": "2025-03-25T06:45:09.438289Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Mapping data shape: (54295, 2)\n", "First 5 rows of mapping data:\n", " ID Gene\n", "3 4 HEBP1\n", "4 5 KCNE4\n", "5 6 BPIFA3\n", "6 7 LOC100129869\n", "7 8 IRG1\n", "Gene expression data shape after mapping: (20353, 70)\n", "First 5 gene symbols after mapping:\n", "Index(['A1BG', 'A1BG-AS1', 'A1CF', 'A2LD1', 'A2M'], dtype='object', name='Gene')\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data shape after normalization: (19847, 70)\n", "First 5 normalized gene symbols:\n", "Index(['A1BG', 'A1BG-AS1', 'A1CF', 'A2M', 'A2ML1'], dtype='object', name='Gene')\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data saved to: ../../output/preprocess/Atherosclerosis/gene_data/GSE154851.csv\n" ] } ], "source": [ "# 1. Determine which columns to use for mapping\n", "# From the previous analysis, we can see:\n", "# - Gene identifiers in gene expression data: numeric IDs like '1', '2', '3' which correspond to the 'ID' column in gene_annotation\n", "# - Gene symbols are in the 'GENE_SYMBOL' column of gene_annotation\n", "\n", "# 2. Create a gene mapping dataframe\n", "# We need to map from 'ID' to 'GENE_SYMBOL'\n", "mapping_data = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='GENE_SYMBOL')\n", "print(f\"Mapping data shape: {mapping_data.shape}\")\n", "print(\"First 5 rows of mapping data:\")\n", "print(mapping_data.head())\n", "\n", "# 3. Apply gene mapping to convert probe-level data to gene-level 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 5 gene symbols after mapping:\")\n", "print(gene_data.index[:5])\n", "\n", "# Let's normalize gene symbols to standard format\n", "gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"Gene expression data shape after normalization: {gene_data.shape}\")\n", "print(\"First 5 normalized gene symbols:\")\n", "print(gene_data.index[:5])\n", "\n", "# Save the gene 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\"Gene expression data saved to: {out_gene_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "ff5344f1", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "edbb3789", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:45:09.440869Z", "iopub.status.busy": "2025-03-25T06:45:09.440739Z", "iopub.status.idle": "2025-03-25T06:45:10.741909Z", "shell.execute_reply": "2025-03-25T06:45:10.741277Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Normalizing gene symbols...\n", "Gene data shape after normalization: (19847, 70)\n", "First 10 normalized gene symbols:\n", "Index(['A1BG', 'A1BG-AS1', 'A1CF', 'A2M', 'A2ML1', 'A2MP1', 'A4GALT', 'A4GNT',\n", " 'AA06', 'AAA1'],\n", " dtype='object', name='Gene')\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data saved to: ../../output/preprocess/Atherosclerosis/gene_data/GSE154851.csv\n", "\n", "Preparing clinical data...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Processed clinical data preview:\n", "{'GSM4681537': [nan, 18.0, 0.0], 'GSM4681538': [nan, 37.0, 0.0], 'GSM4681539': [nan, 59.0, 0.0], 'GSM4681540': [nan, 36.0, 0.0], 'GSM4681541': [nan, 56.0, 0.0], 'GSM4681542': [nan, 22.0, 0.0], 'GSM4681543': [nan, 53.0, 0.0], 'GSM4681544': [nan, 41.0, 1.0], 'GSM4681545': [nan, 33.0, 0.0], 'GSM4681546': [nan, 52.0, 0.0], 'GSM4681547': [nan, 42.0, 0.0], 'GSM4681548': [nan, 28.0, 0.0], 'GSM4681549': [nan, 45.0, 0.0], 'GSM4681550': [nan, 41.0, 0.0], 'GSM4681551': [nan, 25.0, 0.0], 'GSM4681552': [nan, 34.0, 0.0], 'GSM4681553': [nan, 40.0, 0.0], 'GSM4681554': [nan, 44.0, 0.0], 'GSM4681555': [nan, 42.0, 0.0], 'GSM4681556': [nan, 39.0, 0.0], 'GSM4681557': [nan, 51.0, 0.0], 'GSM4681558': [nan, 41.0, 0.0], 'GSM4681559': [nan, 52.0, 0.0], 'GSM4681560': [nan, 34.0, 0.0], 'GSM4681561': [nan, 21.0, 0.0], 'GSM4681562': [nan, 23.0, 0.0], 'GSM4681563': [nan, 32.0, 0.0], 'GSM4681564': [nan, 39.0, 0.0], 'GSM4681565': [nan, 71.0, 0.0], 'GSM4681566': [nan, 23.0, 0.0], 'GSM4681567': [nan, 44.0, 0.0], 'GSM4681568': [nan, 26.0, 0.0], 'GSM4681569': [nan, 31.0, 0.0], 'GSM4681570': [nan, 24.0, 0.0], 'GSM4681571': [nan, 23.0, 0.0], 'GSM4681572': [nan, 31.0, 1.0], 'GSM4681573': [nan, 30.0, 0.0], 'GSM4681574': [nan, 47.0, 0.0], 'GSM4681575': [nan, 30.0, 0.0], 'GSM4681576': [nan, 24.0, 0.0], 'GSM4681577': [nan, 35.0, 0.0], 'GSM4681578': [nan, 25.0, 0.0], 'GSM4681579': [nan, 25.0, 0.0], 'GSM4681580': [nan, 33.0, 0.0], 'GSM4681581': [nan, 19.0, 0.0], 'GSM4681582': [nan, 23.0, 0.0], 'GSM4681583': [nan, 36.0, 0.0], 'GSM4681584': [nan, 26.0, 0.0], 'GSM4681585': [nan, 27.0, 0.0], 'GSM4681586': [nan, 28.0, 0.0], 'GSM4681587': [nan, 34.0, 0.0], 'GSM4681588': [nan, 30.0, 0.0], 'GSM4681589': [nan, 39.0, 0.0], 'GSM4681590': [nan, 32.0, 0.0], 'GSM4681591': [nan, 26.0, 0.0], 'GSM4681592': [nan, 22.0, 0.0], 'GSM4681593': [nan, 25.0, 0.0], 'GSM4681594': [nan, 32.0, 0.0], 'GSM4681595': [nan, 33.0, 0.0], 'GSM4681596': [nan, 41.0, 0.0], 'GSM4681597': [nan, 31.0, 0.0], 'GSM4681598': [nan, 48.0, 0.0], 'GSM4681599': [nan, 38.0, 0.0], 'GSM4681600': [nan, 30.0, 0.0], 'GSM4681601': [nan, 27.0, 0.0], 'GSM4681602': [nan, 23.0, 0.0], 'GSM4681603': [nan, 41.0, 0.0], 'GSM4681604': [nan, 36.0, 0.0], 'GSM4681605': [nan, 34.0, 0.0], 'GSM4681606': [nan, 54.0, 0.0]}\n", "Clinical data saved to: ../../output/preprocess/Atherosclerosis/clinical_data/GSE154851.csv\n", "\n", "Linking clinical and genetic data...\n", "Linked data shape: (70, 19850)\n", "Linked data preview (first 5 samples, 5 features):\n", " Atherosclerosis Age Gender A1BG A1BG-AS1\n", "GSM4681537 NaN 18.0 0.0 1152.992618 325.996309\n", "GSM4681538 NaN 37.0 0.0 609.393488 143.196744\n", "GSM4681539 NaN 59.0 0.0 795.437693 196.218847\n", "GSM4681540 NaN 36.0 0.0 950.035308 210.517654\n", "GSM4681541 NaN 56.0 0.0 1288.902356 340.701178\n", "\n", "Handling missing values...\n", "Linked data shape after handling missing values: (0, 2)\n", "\n", "Checking for bias in dataset features...\n", "Abnormality detected in the cohort: GSE154851. Preprocessing failed.\n", "\n", "Dataset validation complete.\n", "Dataset usable for association studies: False\n", "Note: This GSE154851 dataset contains gene expression data from SLE patients with increased risk of atherosclerosis. While gene expression data is available, explicit atherosclerosis trait data is not provided, making the dataset unsuitable for our specific atherosclerosis association study.\n", "Dataset deemed not usable for associative studies. Linked data not saved.\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", "_, 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", "# Since Step 2 identified no atherosclerosis trait data is available,\n", "# but we still need to correctly extract age and gender data for completeness\n", "# Define conversion functions for age and gender\n", "def convert_age(value):\n", " try:\n", " if isinstance(value, str) and 'age:' in value:\n", " # Extract the number from strings like \"age: 18y\"\n", " age_str = value.split(':')[1].strip()\n", " return int(age_str.replace('y', ''))\n", " return None\n", " except:\n", " return None\n", "\n", "def convert_gender(value):\n", " try:\n", " if isinstance(value, str) and 'gender:' in value:\n", " gender = value.split(':')[1].strip().lower()\n", " if gender == 'female':\n", " return 0\n", " elif gender == 'male':\n", " return 1\n", " return None\n", " except:\n", " return None\n", "\n", "# Extract demographic data we do have\n", "age_row = 2 # Row for age information\n", "gender_row = 1 # Row for gender information\n", "\n", "# Create a processed clinical dataframe with at least demographic information\n", "clinical_df = pd.DataFrame()\n", "if age_row is not None:\n", " age_data = get_feature_data(clinical_data, age_row, 'Age', convert_age)\n", " clinical_df = pd.concat([clinical_df, age_data], axis=0) if not clinical_df.empty else age_data\n", "if gender_row is not None:\n", " gender_data = get_feature_data(clinical_data, gender_row, 'Gender', convert_gender)\n", " clinical_df = pd.concat([clinical_df, gender_data], axis=0) if not clinical_df.empty else gender_data\n", "\n", "# Add an empty Atherosclerosis column to maintain the expected structure\n", "atherosclerosis_row = pd.DataFrame([pd.Series(float('nan'), index=clinical_df.columns)], index=[trait])\n", "clinical_df = pd.concat([atherosclerosis_row, clinical_df], axis=0)\n", "\n", "print(\"Processed clinical data preview:\")\n", "print(preview_df(clinical_df))\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 samples, 5 features):\")\n", "print(linked_data.iloc[:5, :5] if linked_data.shape[0] > 0 and linked_data.shape[1] > 5 else 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", "# Since we know we don't have trait data, we'll set is_biased to False as it's neither biased nor unbiased\n", "# The validation function still needs to receive a parameter though\n", "is_biased = False\n", "\n", "# 6. Conduct final quality validation\n", "note = \"This GSE154851 dataset contains gene expression data from SLE patients with increased risk of atherosclerosis. While gene expression data is available, explicit atherosclerosis trait data is not provided, making the dataset unsuitable for our specific atherosclerosis association study.\"\n", "\n", "is_usable = validate_and_save_cohort_info(\n", " is_final=True,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=True,\n", " is_trait_available=False, # No trait data available\n", " is_biased=is_biased,\n", " df=linked_data_clean,\n", " note=note\n", ")\n", "\n", "print(\"\\nDataset validation complete.\")\n", "print(f\"Dataset usable for association studies: {is_usable}\")\n", "print(f\"Note: {note}\")\n", "\n", "# 7. Don't save the linked data since it's not usable (no trait information)\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 }