{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "e35e2ffb", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:55:14.653886Z", "iopub.status.busy": "2025-03-25T07:55:14.653660Z", "iopub.status.idle": "2025-03-25T07:55:14.820742Z", "shell.execute_reply": "2025-03-25T07:55:14.820396Z" } }, "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 = \"Lupus_(Systemic_Lupus_Erythematosus)\"\n", "cohort = \"GSE154851\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Lupus_(Systemic_Lupus_Erythematosus)\"\n", "in_cohort_dir = \"../../input/GEO/Lupus_(Systemic_Lupus_Erythematosus)/GSE154851\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Lupus_(Systemic_Lupus_Erythematosus)/GSE154851.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Lupus_(Systemic_Lupus_Erythematosus)/gene_data/GSE154851.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Lupus_(Systemic_Lupus_Erythematosus)/clinical_data/GSE154851.csv\"\n", "json_path = \"../../output/preprocess/Lupus_(Systemic_Lupus_Erythematosus)/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "aa103b26", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "5566e043", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:55:14.822203Z", "iopub.status.busy": "2025-03-25T07:55:14.822064Z", "iopub.status.idle": "2025-03-25T07:55:15.058256Z", "shell.execute_reply": "2025-03-25T07:55:15.057918Z" } }, "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": "dd3125d9", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "73efc7f4", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:55:15.059532Z", "iopub.status.busy": "2025-03-25T07:55:15.059412Z", "iopub.status.idle": "2025-03-25T07:55:15.065019Z", "shell.execute_reply": "2025-03-25T07:55:15.064713Z" } }, "outputs": [], "source": [ "# Check gene expression data availability\n", "import os\n", "import pandas as pd\n", "import json\n", "from typing import Optional, Callable, Dict, Any\n", "\n", "# 1. Gene Expression Data Availability\n", "# From the background information, we can see that this dataset used \n", "# \"Sureprint G3 Human Gene Expression 8x60K Microarray kit\" which indicates gene expression data\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1. Trait (SLE)\n", "# From the sample characteristics dictionary, we don't see explicit trait information\n", "# The trait isn't directly available in the sample characteristics\n", "trait_row = None\n", "\n", "def convert_trait(trait_str):\n", " if trait_str is None:\n", " return None\n", " if ':' in trait_str:\n", " trait_value = trait_str.split(':', 1)[1].strip().lower()\n", " # Assuming SLE patients are coded as 1, healthy controls as 0\n", " if any(term in trait_value for term in ['sle', 'lupus', 'patient', 'case', 'disease']):\n", " return 1\n", " elif any(term in trait_value for term in ['control', 'healthy', 'normal']):\n", " return 0\n", " return None\n", "\n", "# 2.2. Age\n", "# Age is available in the sample characteristics dictionary at key 2\n", "age_row = 2\n", "\n", "def convert_age(age_str):\n", " try:\n", " if age_str is None:\n", " return None\n", " # Extract the age value after the colon\n", " if ':' in age_str:\n", " age_part = age_str.split(':', 1)[1].strip()\n", " # Remove 'y' and convert to float\n", " return float(age_part.replace('y', '').strip())\n", " return None\n", " except:\n", " return None\n", "\n", "# 2.3. Gender\n", "# Gender is available in the sample characteristics dictionary at key 1\n", "gender_row = 1\n", "\n", "def convert_gender(gender_str):\n", " if gender_str is None:\n", " return None\n", " if ':' in gender_str:\n", " gender = gender_str.split(':', 1)[1].strip().lower()\n", " if gender == 'female':\n", " return 0\n", " elif gender == 'male':\n", " return 1\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Trait data is not available in the sample characteristics\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 should skip the clinical feature extraction step\n", "if trait_row is not None:\n", " # This block won't execute but is kept for completeness\n", " clinical_data = pd.read_csv(os.path.join(in_cohort_dir, \"clinical_data.csv\"))\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(\"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", " selected_clinical_df.to_csv(out_clinical_data_file, index=False)\n" ] }, { "cell_type": "markdown", "id": "a98c5397", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "b87f4021", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:55:15.066141Z", "iopub.status.busy": "2025-03-25T07:55:15.066033Z", "iopub.status.idle": "2025-03-25T07:55:15.484626Z", "shell.execute_reply": "2025-03-25T07:55:15.484233Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "This appears to be a SuperSeries. Looking at the SOFT file to find potential subseries:\n", "No subseries references found in the first 1000 lines of the SOFT file.\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene data extraction result:\n", "Number of rows: 62976\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. First get the path to the soft and matrix files\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# 2. Looking more carefully at the background information\n", "# This is a SuperSeries which doesn't contain direct gene expression data\n", "# Need to investigate the soft file to find the subseries\n", "print(\"This appears to be a SuperSeries. Looking at the SOFT file to find potential subseries:\")\n", "\n", "# Open the SOFT file to try to identify subseries\n", "with gzip.open(soft_file, 'rt') as f:\n", " subseries_lines = []\n", " for i, line in enumerate(f):\n", " if 'Series_relation' in line and 'SuperSeries of' in line:\n", " subseries_lines.append(line.strip())\n", " if i > 1000: # Limit search to first 1000 lines\n", " break\n", "\n", "# Display the subseries found\n", "if subseries_lines:\n", " print(\"Found potential subseries references:\")\n", " for line in subseries_lines:\n", " print(line)\n", "else:\n", " print(\"No subseries references found in the first 1000 lines of the SOFT file.\")\n", "\n", "# Despite trying to extract gene data, we expect it might fail because this is a SuperSeries\n", "try:\n", " gene_data = get_genetic_data(matrix_file)\n", " print(\"\\nGene data extraction result:\")\n", " print(\"Number of rows:\", len(gene_data))\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", " print(\"This confirms the dataset is a SuperSeries without direct gene expression data.\")\n" ] }, { "cell_type": "markdown", "id": "9b437f4a", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "3b3268ab", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:55:15.485955Z", "iopub.status.busy": "2025-03-25T07:55:15.485832Z", "iopub.status.idle": "2025-03-25T07:55:15.487759Z", "shell.execute_reply": "2025-03-25T07:55:15.487472Z" } }, "outputs": [], "source": [ "# Gene Identifier Review\n", "# The identifiers shown are simply numbers (1, 2, 3, etc.) which are clearly not human gene symbols.\n", "# These appear to be probe indices or database-specific identifiers that would need to be mapped\n", "# to proper human gene symbols for meaningful analysis.\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "6309ba48", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "cad38955", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:55:15.488995Z", "iopub.status.busy": "2025-03-25T07:55:15.488879Z", "iopub.status.idle": "2025-03-25T07:55:21.833974Z", "shell.execute_reply": "2025-03-25T07:55:21.833520Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene annotation preview:\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" ] } ], "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. Use the 'preview_df' function from the library to preview the data and print out the results.\n", "print(\"Gene annotation preview:\")\n", "print(preview_df(gene_annotation))\n" ] }, { "cell_type": "markdown", "id": "2caf1b9d", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "276ddd29", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:55:21.835528Z", "iopub.status.busy": "2025-03-25T07:55:21.835404Z", "iopub.status.idle": "2025-03-25T07:55:22.303951Z", "shell.execute_reply": "2025-03-25T07:55:22.303600Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Created mapping dataframe with 54295 entries\n", "First few rows of mapping dataframe:\n", " ID Gene\n", "3 4 HEBP1\n", "4 5 KCNE4\n", "5 6 BPIFA3\n", "6 7 LOC100129869\n", "7 8 IRG1\n", "\n", "Converted to gene expression data with 20353 genes\n", "First few gene symbols:\n", "Index(['A1BG', 'A1BG-AS1', 'A1CF', 'A2LD1', 'A2M', 'A2ML1', 'A2MP1', 'A4GALT',\n", " 'A4GNT', 'AA06'],\n", " dtype='object', name='Gene')\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "After normalizing gene symbols, we have 19847 unique genes\n", "First few normalized gene symbols:\n", "Index(['A1BG', 'A1BG-AS1', 'A1CF', 'A2M', 'A2ML1', 'A2MP1', 'A4GALT', 'A4GNT',\n", " 'AA06', 'AAA1'],\n", " dtype='object', name='Gene')\n" ] } ], "source": [ "# 1. Identify which columns in the gene annotation dataframe correspond to probe IDs and gene symbols\n", "prob_col = 'ID' # Probe identifiers in gene expression data match the 'ID' column\n", "gene_col = 'GENE_SYMBOL' # Gene symbols are stored in the 'GENE_SYMBOL' column\n", "\n", "# 2. Create a gene mapping dataframe using these two columns\n", "mapping_df = get_gene_mapping(gene_annotation, prob_col, gene_col)\n", "print(f\"Created mapping dataframe with {len(mapping_df)} entries\")\n", "print(\"First few rows of mapping dataframe:\")\n", "print(mapping_df.head())\n", "\n", "# 3. Apply the gene mapping to convert probe-level measurements to gene expression data\n", "gene_data = apply_gene_mapping(gene_data, mapping_df)\n", "print(f\"\\nConverted to gene expression data with {len(gene_data)} genes\")\n", "print(\"First few gene symbols:\")\n", "print(gene_data.index[:10])\n", "\n", "# Apply normalization to gene symbols to handle potential synonyms\n", "gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"\\nAfter normalizing gene symbols, we have {len(gene_data)} unique genes\")\n", "print(\"First few normalized gene symbols:\")\n", "print(gene_data.index[:10])\n" ] }, { "cell_type": "markdown", "id": "982e73ca", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "9100f624", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:55:22.305359Z", "iopub.status.busy": "2025-03-25T07:55:22.305233Z", "iopub.status.idle": "2025-03-25T07:55:23.274017Z", "shell.execute_reply": "2025-03-25T07:55:23.273675Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Top 10 gene indices before normalization: ['A1BG', 'A1BG-AS1', 'A1CF', 'A2M', 'A2ML1', 'A2MP1', 'A4GALT', 'A4GNT', 'AA06', 'AAA1']\n", "Top 10 gene indices after normalization: ['A1BG', 'A1BG-AS1', 'A1CF', 'A2M', 'A2ML1', 'A2MP1', 'A4GALT', 'A4GNT', 'AA06', 'AAA1']\n", "Shape of normalized gene data: (19847, 70)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Saved normalized gene data to ../../output/preprocess/Lupus_(Systemic_Lupus_Erythematosus)/gene_data/GSE154851.csv\n", "Clinical data not available for Lupus_(Systemic_Lupus_Erythematosus) in this dataset\n", "Shape of linked data: (70, 19847)\n", "Dataset validation failed: No lupus trait data available. Final linked data not saved.\n" ] } ], "source": [ "# 1. Normalize gene symbols in the gene expression data\n", "print(f\"Top 10 gene indices before normalization: {gene_data.index[:10].tolist()}\")\n", "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"Top 10 gene indices after normalization: {normalized_gene_data.index[:10].tolist()}\")\n", "print(f\"Shape of normalized gene data: {normalized_gene_data.shape}\")\n", "\n", "# Create directory for gene data file if it doesn't exist\n", "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", "# Save the normalized gene data\n", "normalized_gene_data.to_csv(out_gene_data_file)\n", "print(f\"Saved normalized gene data to {out_gene_data_file}\")\n", "\n", "# 2. Link the clinical and genetic data\n", "# Based on our analysis in Step 2, we determined that this dataset does not contain \n", "# lupus trait data. The dataset is about recurrent pregnancy losses and unexplained infertility,\n", "# not Lupus (Systemic Lupus Erythematosus).\n", "\n", "# Create a dummy clinical dataframe to properly document the absence of trait data\n", "sample_ids = normalized_gene_data.columns.tolist()\n", "clinical_df = pd.DataFrame(index=sample_ids)\n", "# We'll create an empty clinical dataframe to accurately represent that we don't have lupus data\n", "print(f\"Clinical data not available for {trait} in this dataset\")\n", "\n", "# 3. Prepare linked data - in this case, it will just be the gene expression data\n", "# with missing clinical information\n", "linked_data = normalized_gene_data.T\n", "print(f\"Shape of linked data: {linked_data.shape}\")\n", "\n", "# 4. We cannot properly handle missing values for trait because the trait data \n", "# doesn't exist in this dataset\n", "\n", "# 5. Since the trait data is completely missing, we shouldn't proceed with bias analysis\n", "is_trait_biased = True # Mark as biased because we have no trait data for lupus\n", "unbiased_linked_data = linked_data # Keep the gene data for reference\n", "\n", "# 6. Conduct quality check and save the cohort information - report that trait data is not available\n", "is_trait_available = False # No trait data for lupus\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=is_trait_available,\n", " is_biased=is_trait_biased,\n", " df=unbiased_linked_data,\n", " note=\"Dataset contains gene expression data from endometrial tissue study of recurrent pregnancy losses \" +\n", " \"and unexplained infertility, not lupus. No lupus trait data available.\"\n", ")\n", "\n", "# 7. Since the linked data is not usable for lupus analysis, we won't save it as a final dataset\n", "if is_usable:\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " unbiased_linked_data.to_csv(out_data_file)\n", " print(f\"Saved processed linked data to {out_data_file}\")\n", "else:\n", " print(\"Dataset validation failed: No lupus trait data available. Final 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 }