{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "394504c0", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:18:02.168910Z", "iopub.status.busy": "2025-03-25T08:18:02.168677Z", "iopub.status.idle": "2025-03-25T08:18:02.332527Z", "shell.execute_reply": "2025-03-25T08:18:02.332102Z" } }, "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 = \"Chronic_kidney_disease\"\n", "cohort = \"GSE142153\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Chronic_kidney_disease\"\n", "in_cohort_dir = \"../../input/GEO/Chronic_kidney_disease/GSE142153\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Chronic_kidney_disease/GSE142153.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Chronic_kidney_disease/gene_data/GSE142153.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Chronic_kidney_disease/clinical_data/GSE142153.csv\"\n", "json_path = \"../../output/preprocess/Chronic_kidney_disease/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "ed80e421", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "878c22bd", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:18:02.333954Z", "iopub.status.busy": "2025-03-25T08:18:02.333819Z", "iopub.status.idle": "2025-03-25T08:18:02.407552Z", "shell.execute_reply": "2025-03-25T08:18:02.407176Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Human PBMCs: Healthy vs Diabetic nephropathy vs ESRD\"\n", "!Series_summary\t\"Transcriptional profiling of human PBMCs comparing healthy controls, patients with diabetic nephropathy and patients with ESRD. PBMCs were analyzed as they mediate inflammatory injury. Goal was to determine effects of increasing severity of diabetic nephropathy on global PBMC gene expression. Microarray analysis of PBMCs taken from patients with varying degrees of diabetic nephropathy.\"\n", "!Series_overall_design\t\"3 condition experiment - Healthy control (10) vs diabetic nephropathy (23) vs ESRD (7)\"\n", "Sample Characteristics Dictionary:\n", "{0: ['tissue: peripheral blood'], 1: ['diagnosis: healthy control', 'diagnosis: diabetic nephropathy', 'diagnosis: ESRD']}\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": "2e77ec63", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "d2dd4c06", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:18:02.408761Z", "iopub.status.busy": "2025-03-25T08:18:02.408657Z", "iopub.status.idle": "2025-03-25T08:18:02.415814Z", "shell.execute_reply": "2025-03-25T08:18:02.415444Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Preview of clinical features:\n", "{'GSM4221568': [0.0], 'GSM4221569': [0.0], 'GSM4221570': [0.0], 'GSM4221571': [0.0], 'GSM4221572': [0.0], 'GSM4221573': [0.0], 'GSM4221574': [0.0], 'GSM4221575': [0.0], 'GSM4221576': [0.0], 'GSM4221577': [0.0], 'GSM4221578': [1.0], 'GSM4221579': [1.0], 'GSM4221580': [1.0], 'GSM4221581': [1.0], 'GSM4221582': [1.0], 'GSM4221583': [1.0], 'GSM4221584': [1.0], 'GSM4221585': [1.0], 'GSM4221586': [1.0], 'GSM4221587': [1.0], 'GSM4221588': [1.0], 'GSM4221589': [1.0], 'GSM4221590': [1.0], 'GSM4221591': [1.0], 'GSM4221592': [1.0], 'GSM4221593': [1.0], 'GSM4221594': [1.0], 'GSM4221595': [1.0], 'GSM4221596': [1.0], 'GSM4221597': [1.0], 'GSM4221598': [1.0], 'GSM4221599': [1.0], 'GSM4221600': [1.0], 'GSM4221601': [1.0], 'GSM4221602': [1.0], 'GSM4221603': [1.0], 'GSM4221604': [1.0], 'GSM4221605': [1.0], 'GSM4221606': [1.0], 'GSM4221607': [1.0]}\n", "Clinical features saved to ../../output/preprocess/Chronic_kidney_disease/clinical_data/GSE142153.csv\n" ] } ], "source": [ "# 1. Gene Expression Data Availability\n", "# Based on the background information, this dataset contains transcriptional profiling data\n", "# which indicates gene expression data is available\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "\n", "# For trait (diabetic nephropathy/chronic kidney disease):\n", "# Row 1 contains diagnosis information with multiple values\n", "trait_row = 1\n", "\n", "# Age data is not available in the sample characteristics\n", "age_row = None\n", "\n", "# Gender data is not available in the sample characteristics\n", "gender_row = None\n", "\n", "# 2.2 Data Type Conversion\n", "\n", "# Convert trait values to binary (0 for control, 1 for disease)\n", "def convert_trait(value):\n", " if isinstance(value, str):\n", " # Extract the value after colon if exists\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Convert based on diagnosis\n", " if 'healthy control' in value.lower():\n", " return 0 # Control\n", " elif 'diabetic nephropathy' in value.lower() or 'esrd' in value.lower():\n", " return 1 # Disease (Diabetic nephropathy or ESRD both indicate kidney disease)\n", " return None\n", "\n", "# Since age data is not available, we define a placeholder function\n", "def convert_age(value):\n", " return None\n", "\n", "# Since gender data is not available, we define a placeholder function\n", "def convert_gender(value):\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Determine if trait data is available\n", "is_trait_available = trait_row is not None\n", "\n", "# Validate and save cohort info\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", " # 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 clinical features dataframe\n", " print(\"Preview of clinical features:\")\n", " print(preview_df(clinical_features_df))\n", " \n", " # Create output directory if it doesn't exist\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " \n", " # Save the clinical features to a CSV file\n", " clinical_features_df.to_csv(out_clinical_data_file)\n", " print(f\"Clinical features saved to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "358db33d", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "378d24ff", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:18:02.416966Z", "iopub.status.busy": "2025-03-25T08:18:02.416864Z", "iopub.status.idle": "2025-03-25T08:18:02.541979Z", "shell.execute_reply": "2025-03-25T08:18:02.541457Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "SOFT file: ../../input/GEO/Chronic_kidney_disease/GSE142153/GSE142153_family.soft.gz\n", "Matrix file: ../../input/GEO/Chronic_kidney_disease/GSE142153/GSE142153_series_matrix.txt.gz\n", "Gene data shape: (30811, 40)\n", "First 20 gene/probe identifiers:\n", "['A_23_P100001', 'A_23_P100022', 'A_23_P100056', 'A_23_P100074', 'A_23_P100111', 'A_23_P100127', 'A_23_P100133', 'A_23_P100141', 'A_23_P100156', 'A_23_P100189', 'A_23_P100203', 'A_23_P100220', 'A_23_P100240', 'A_23_P10025', 'A_23_P100278', 'A_23_P100292', 'A_23_P100315', 'A_23_P100344', 'A_23_P100355', 'A_23_P100386']\n" ] } ], "source": [ "# 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", "print(f\"SOFT file: {soft_file}\")\n", "print(f\"Matrix file: {matrix_file}\")\n", "\n", "# Set gene availability flag\n", "is_gene_available = True # Assume gene data is available\n", "\n", "# Extract gene data\n", "try:\n", " # Extract gene data from the matrix file\n", " gene_data = get_genetic_data(matrix_file)\n", " print(f\"Gene data shape: {gene_data.shape}\")\n", " \n", " # Print the first 20 gene/probe identifiers\n", " print(\"First 20 gene/probe identifiers:\")\n", " print(gene_data.index[:20].tolist())\n", "except Exception as e:\n", " print(f\"Error extracting gene data: {e}\")\n", " print(f\"File path: {matrix_file}\")\n", " print(\"Please check if the file exists and contains the expected markers.\")\n" ] }, { "cell_type": "markdown", "id": "550aa3ea", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "182fdc77", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:18:02.543412Z", "iopub.status.busy": "2025-03-25T08:18:02.543298Z", "iopub.status.idle": "2025-03-25T08:18:02.545385Z", "shell.execute_reply": "2025-03-25T08:18:02.545014Z" } }, "outputs": [], "source": [ "# Looking at the gene identifiers, these are Agilent microarray probe IDs (starting with 'A_23_P'),\n", "# not standard human gene symbols. These probe IDs will need to be mapped to gene symbols.\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "dbad4b86", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "5dd772d3", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:18:02.546720Z", "iopub.status.busy": "2025-03-25T08:18:02.546619Z", "iopub.status.idle": "2025-03-25T08:18:04.675136Z", "shell.execute_reply": "2025-03-25T08:18:04.674493Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene annotation preview:\n", "Columns in gene annotation: ['ID', 'SPOT_ID', 'CONTROL_TYPE', 'REFSEQ', 'GB_ACC', 'GENE', 'GENE_SYMBOL', 'GENE_NAME', 'UNIGENE_ID', 'ENSEMBL_ID', 'TIGR_ID', 'ACCESSION_STRING', 'CHROMOSOMAL_LOCATION', 'CYTOBAND', 'DESCRIPTION', 'GO_ID', 'SEQUENCE']\n", "{'ID': ['A_23_P100001', 'A_23_P100011', 'A_23_P100022', 'A_23_P100056', 'A_23_P100074'], 'SPOT_ID': ['A_23_P100001', 'A_23_P100011', 'A_23_P100022', 'A_23_P100056', 'A_23_P100074'], 'CONTROL_TYPE': ['FALSE', 'FALSE', 'FALSE', 'FALSE', 'FALSE'], 'REFSEQ': ['NM_207446', 'NM_005829', 'NM_014848', 'NM_194272', 'NM_020371'], 'GB_ACC': ['NM_207446', 'NM_005829', 'NM_014848', 'NM_194272', 'NM_020371'], 'GENE': [400451.0, 10239.0, 9899.0, 348093.0, 57099.0], 'GENE_SYMBOL': ['FAM174B', 'AP3S2', 'SV2B', 'RBPMS2', 'AVEN'], 'GENE_NAME': ['family with sequence similarity 174, member B', 'adaptor-related protein complex 3, sigma 2 subunit', 'synaptic vesicle glycoprotein 2B', 'RNA binding protein with multiple splicing 2', 'apoptosis, caspase activation inhibitor'], 'UNIGENE_ID': ['Hs.27373', 'Hs.632161', 'Hs.21754', 'Hs.436518', 'Hs.555966'], 'ENSEMBL_ID': ['ENST00000557398', nan, 'ENST00000557410', 'ENST00000300069', 'ENST00000306730'], 'TIGR_ID': [nan, nan, nan, nan, nan], 'ACCESSION_STRING': ['ref|NM_207446|ens|ENST00000557398|ens|ENST00000553393|ens|ENST00000327355', 'ref|NM_005829|ref|NM_001199058|ref|NR_023361|ref|NR_037582', 'ref|NM_014848|ref|NM_001167580|ens|ENST00000557410|ens|ENST00000330276', 'ref|NM_194272|ens|ENST00000300069|gb|AK127873|gb|AK124123', 'ref|NM_020371|ens|ENST00000306730|gb|AF283508|gb|BC010488'], 'CHROMOSOMAL_LOCATION': ['chr15:93160848-93160789', 'chr15:90378743-90378684', 'chr15:91838329-91838388', 'chr15:65032375-65032316', 'chr15:34158739-34158680'], 'CYTOBAND': ['hs|15q26.1', 'hs|15q26.1', 'hs|15q26.1', 'hs|15q22.31', 'hs|15q14'], 'DESCRIPTION': ['Homo sapiens family with sequence similarity 174, member B (FAM174B), mRNA [NM_207446]', 'Homo sapiens adaptor-related protein complex 3, sigma 2 subunit (AP3S2), transcript variant 1, mRNA [NM_005829]', 'Homo sapiens synaptic vesicle glycoprotein 2B (SV2B), transcript variant 1, mRNA [NM_014848]', 'Homo sapiens RNA binding protein with multiple splicing 2 (RBPMS2), mRNA [NM_194272]', 'Homo sapiens apoptosis, caspase activation inhibitor (AVEN), mRNA [NM_020371]'], 'GO_ID': ['GO:0016020(membrane)|GO:0016021(integral to membrane)', 'GO:0005794(Golgi apparatus)|GO:0006886(intracellular protein transport)|GO:0008565(protein transporter activity)|GO:0016020(membrane)|GO:0016192(vesicle-mediated transport)|GO:0030117(membrane coat)|GO:0030659(cytoplasmic vesicle membrane)|GO:0031410(cytoplasmic vesicle)', 'GO:0001669(acrosomal vesicle)|GO:0006836(neurotransmitter transport)|GO:0016020(membrane)|GO:0016021(integral to membrane)|GO:0022857(transmembrane transporter activity)|GO:0030054(cell junction)|GO:0030672(synaptic vesicle membrane)|GO:0031410(cytoplasmic vesicle)|GO:0045202(synapse)', 'GO:0000166(nucleotide binding)|GO:0003676(nucleic acid binding)', 'GO:0005515(protein binding)|GO:0005622(intracellular)|GO:0005624(membrane fraction)|GO:0006915(apoptosis)|GO:0006916(anti-apoptosis)|GO:0012505(endomembrane system)|GO:0016020(membrane)'], 'SEQUENCE': ['ATCTCATGGAAAAGCTGGATTCCTCTGCCTTACGCAGAAACACCCGGGCTCCATCTGCCA', 'TCAAGTATTGGCCTGACATAGAGTCCTTAAGACAAGCAAAGACAAGCAAGGCAAGCACGT', 'ATGTCGGCTGTGGAGGGTTAAAGGGATGAGGCTTTCCTTTGTTTAGCAAATCTGTTCACA', 'CCCTGTCAGATAAGTTTAATGTTTAGTTTGAGGCATGAAGAAGAAAAGGGTTTCCATTCT', 'GACCAGCCAGTTTACAAGCATGTCTCAAGCTAGTGTGTTCCATTATGCTCACAGCAGTAA']}\n", "\n", "Complete sample of a few rows:\n", " ID SPOT_ID CONTROL_TYPE REFSEQ GB_ACC GENE GENE_SYMBOL GENE_NAME UNIGENE_ID ENSEMBL_ID TIGR_ID ACCESSION_STRING CHROMOSOMAL_LOCATION CYTOBAND DESCRIPTION GO_ID SEQUENCE\n", "0 A_23_P100001 A_23_P100001 FALSE NM_207446 NM_207446 400451.0 FAM174B family with sequence similarity 174, member B Hs.27373 ENST00000557398 NaN ref|NM_207446|ens|ENST00000557398|ens|ENST00000553393|ens|ENST00000327355 chr15:93160848-93160789 hs|15q26.1 Homo sapiens family with sequence similarity 174, member B (FAM174B), mRNA [NM_207446] GO:0016020(membrane)|GO:0016021(integral to membrane) ATCTCATGGAAAAGCTGGATTCCTCTGCCTTACGCAGAAACACCCGGGCTCCATCTGCCA\n", "1 A_23_P100011 A_23_P100011 FALSE NM_005829 NM_005829 10239.0 AP3S2 adaptor-related protein complex 3, sigma 2 subunit Hs.632161 NaN NaN ref|NM_005829|ref|NM_001199058|ref|NR_023361|ref|NR_037582 chr15:90378743-90378684 hs|15q26.1 Homo sapiens adaptor-related protein complex 3, sigma 2 subunit (AP3S2), transcript variant 1, mRNA [NM_005829] GO:0005794(Golgi apparatus)|GO:0006886(intracellular protein transport)|GO:0008565(protein transporter activity)|GO:0016020(membrane)|GO:0016192(vesicle-mediated transport)|GO:0030117(membrane coat)|GO:0030659(cytoplasmic vesicle membrane)|GO:0031410(cytoplasmic vesicle) TCAAGTATTGGCCTGACATAGAGTCCTTAAGACAAGCAAAGACAAGCAAGGCAAGCACGT\n", "2 A_23_P100022 A_23_P100022 FALSE NM_014848 NM_014848 9899.0 SV2B synaptic vesicle glycoprotein 2B Hs.21754 ENST00000557410 NaN ref|NM_014848|ref|NM_001167580|ens|ENST00000557410|ens|ENST00000330276 chr15:91838329-91838388 hs|15q26.1 Homo sapiens synaptic vesicle glycoprotein 2B (SV2B), transcript variant 1, mRNA [NM_014848] GO:0001669(acrosomal vesicle)|GO:0006836(neurotransmitter transport)|GO:0016020(membrane)|GO:0016021(integral to membrane)|GO:0022857(transmembrane transporter activity)|GO:0030054(cell junction)|GO:0030672(synaptic vesicle membrane)|GO:0031410(cytoplasmic vesicle)|GO:0045202(synapse) ATGTCGGCTGTGGAGGGTTAAAGGGATGAGGCTTTCCTTTGTTTAGCAAATCTGTTCACA\n", "\n", "Potential gene-related columns: ['ID', 'SPOT_ID', 'GENE', 'GENE_SYMBOL', 'GENE_NAME', 'UNIGENE_ID', 'ENSEMBL_ID', 'TIGR_ID', 'GO_ID']\n", "\n", "Sample mappings from 'ID' to 'GENE_SYMBOL':\n", " ID GENE_SYMBOL\n", "0 A_23_P100001 FAM174B\n", "1 A_23_P100011 AP3S2\n", "2 A_23_P100022 SV2B\n", "3 A_23_P100056 RBPMS2\n", "4 A_23_P100074 AVEN\n", "5 A_23_P100092 ZSCAN29\n", "6 A_23_P100103 VPS39\n", "7 A_23_P100111 CHP\n", "8 A_23_P100127 CASC5\n", "9 A_23_P100133 ATMIN\n", "\n", "Number of probes with gene ID mappings: 30936\n", "Sample of valid mappings:\n", " ID GENE_SYMBOL\n", "0 A_23_P100001 FAM174B\n", "1 A_23_P100011 AP3S2\n", "2 A_23_P100022 SV2B\n", "3 A_23_P100056 RBPMS2\n", "4 A_23_P100074 AVEN\n" ] } ], "source": [ "# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\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", "# Get a more complete view to understand the annotation structure\n", "print(\"\\nComplete sample of a few rows:\")\n", "print(gene_annotation.iloc[:3].to_string())\n", "\n", "# Check if there are any columns that might contain gene information beyond what we've seen\n", "potential_gene_columns = [col for col in gene_annotation.columns if \n", " any(term in col.upper() for term in [\"GENE\", \"SYMBOL\", \"NAME\", \"ID\"])]\n", "print(f\"\\nPotential gene-related columns: {potential_gene_columns}\")\n", "\n", "# Look for additional columns that might contain gene symbols\n", "# Since we only have 'ID' and 'ENTREZ_GENE_ID', check if we need to use Entrez IDs for mapping\n", "gene_id_col = 'ID'\n", "gene_symbol_col = None\n", "\n", "# Check various potential column names for gene symbols\n", "for col_name in ['GENE_SYMBOL', 'SYMBOL', 'GENE', 'GENE_NAME', 'GB_ACC']:\n", " if col_name in gene_annotation.columns:\n", " gene_symbol_col = col_name\n", " break\n", "\n", "# If no dedicated symbol column is found, we'll need to use ENTREZ_GENE_ID\n", "if gene_symbol_col is None and 'ENTREZ_GENE_ID' in gene_annotation.columns:\n", " gene_symbol_col = 'ENTREZ_GENE_ID'\n", " print(\"\\nNo direct gene symbol column found. Will use Entrez Gene IDs for mapping.\")\n", "\n", "if gene_id_col in gene_annotation.columns and gene_symbol_col is not None:\n", " print(f\"\\nSample mappings from '{gene_id_col}' to '{gene_symbol_col}':\")\n", " sample_mappings = gene_annotation[[gene_id_col, gene_symbol_col]].head(10)\n", " print(sample_mappings)\n", " \n", " # Check for non-null mappings to confirm data quality\n", " non_null_mappings = gene_annotation[[gene_id_col, gene_symbol_col]].dropna(subset=[gene_symbol_col])\n", " print(f\"\\nNumber of probes with gene ID mappings: {len(non_null_mappings)}\")\n", " print(f\"Sample of valid mappings:\")\n", " print(non_null_mappings.head(5))\n", "else:\n", " print(\"Required mapping columns not found in the annotation data. Will need to explore alternative mapping approaches.\")\n" ] }, { "cell_type": "markdown", "id": "413446a6", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "18cd37cd", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:18:04.677016Z", "iopub.status.busy": "2025-03-25T08:18:04.676897Z", "iopub.status.idle": "2025-03-25T08:18:05.134533Z", "shell.execute_reply": "2025-03-25T08:18:05.133902Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Using 'ID' as probe identifier column and 'GENE_SYMBOL' as gene symbol column\n", "Gene mapping dataframe shape: (30936, 2)\n", "Sample of gene mapping:\n", " ID Gene\n", "0 A_23_P100001 FAM174B\n", "1 A_23_P100011 AP3S2\n", "2 A_23_P100022 SV2B\n", "3 A_23_P100056 RBPMS2\n", "4 A_23_P100074 AVEN\n", "Gene expression data shape after mapping: (18440, 40)\n", "First few rows and columns of gene expression data:\n", " GSM4221568 GSM4221569 GSM4221570 GSM4221571 GSM4221572\n", "Gene \n", "A1BG 1.689609 0.116657 0.729824 1.233267 -0.753530\n", "A1BG-AS1 1.735950 1.614540 1.115200 0.556956 0.662771\n", "A1CF -5.546720 -6.946890 -9.237430 -7.895080 -6.992950\n", "A2LD1 1.611080 1.368170 0.811205 1.717300 1.131080\n", "A2M -7.113060 -6.750490 -6.552580 -6.926450 -6.712910\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data saved to ../../output/preprocess/Chronic_kidney_disease/gene_data/GSE142153.csv\n" ] } ], "source": [ "# 1. Determine which columns in gene_annotation contain probe IDs and gene symbols\n", "# Based on the preview, 'ID' contains probe identifiers and 'GENE_SYMBOL' contains gene symbols\n", "probe_id_col = 'ID'\n", "gene_symbol_col = 'GENE_SYMBOL'\n", "\n", "print(f\"Using '{probe_id_col}' as probe identifier column and '{gene_symbol_col}' as gene symbol column\")\n", "\n", "# 2. Create a gene mapping dataframe using the two columns\n", "gene_mapping = get_gene_mapping(gene_annotation, probe_id_col, gene_symbol_col)\n", "print(f\"Gene mapping dataframe shape: {gene_mapping.shape}\")\n", "print(\"Sample of gene mapping:\")\n", "print(gene_mapping.head())\n", "\n", "# 3. Apply the gene mapping to convert probe-level measurements to gene-level expression data\n", "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n", "print(f\"Gene expression data shape after mapping: {gene_data.shape}\")\n", "print(\"First few rows and columns of gene expression data:\")\n", "print(gene_data.iloc[:5, :5])\n", "\n", "# Save gene data to CSV file\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": "07ddffb8", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "20477b22", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:18:05.136736Z", "iopub.status.busy": "2025-03-25T08:18:05.136581Z", "iopub.status.idle": "2025-03-25T08:18:12.923696Z", "shell.execute_reply": "2025-03-25T08:18:12.923210Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Loaded gene data shape: (18440, 40)\n", "Normalized gene data shape: (18202, 40)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data saved to ../../output/preprocess/Chronic_kidney_disease/gene_data/GSE142153.csv\n", "Loaded clinical data shape: (1, 40)\n", "Linked data shape: (40, 18203)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data shape after handling missing values: (40, 18203)\n", "For the feature 'Chronic_kidney_disease', the least common label is '0.0' with 10 occurrences. This represents 25.00% of the dataset.\n", "The distribution of the feature 'Chronic_kidney_disease' in this dataset is fine.\n", "\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data saved to ../../output/preprocess/Chronic_kidney_disease/GSE142153.csv\n" ] } ], "source": [ "# 1. Normalize gene symbols in the gene expression data\n", "try:\n", " gene_data = pd.read_csv(out_gene_data_file, index_col=0)\n", " print(f\"Loaded gene data shape: {gene_data.shape}\")\n", " \n", " # Apply normalization\n", " gene_data = normalize_gene_symbols_in_index(gene_data)\n", " print(f\"Normalized gene data shape: {gene_data.shape}\")\n", " \n", " # Save the normalized 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\"Normalized gene data saved to {out_gene_data_file}\")\n", " is_gene_available = True\n", "except Exception as e:\n", " print(f\"Error normalizing gene data: {e}\")\n", " is_gene_available = False\n", "\n", "# 2. Load clinical data that was already processed and saved\n", "try:\n", " clinical_data = pd.read_csv(out_clinical_data_file, index_col=0)\n", " print(f\"Loaded clinical data shape: {clinical_data.shape}\")\n", " is_trait_available = True\n", "except Exception as e:\n", " print(f\"Error loading clinical data: {e}\")\n", " is_trait_available = False\n", "\n", "# 3. Link clinical and genetic data if both are available\n", "if is_trait_available and is_gene_available:\n", " try:\n", " # Link the clinical and genetic data\n", " linked_data = geo_link_clinical_genetic_data(clinical_data, gene_data)\n", " print(f\"Linked data shape: {linked_data.shape}\")\n", " \n", " # Handle missing values\n", " linked_data = handle_missing_values(linked_data, trait)\n", " print(f\"Linked data shape after handling missing values: {linked_data.shape}\")\n", " \n", " # Check for bias in trait and demographic features\n", " is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n", " \n", " # Validate the data quality and save cohort info\n", " note = \"Dataset contains gene expression data from peripheral blood of healthy controls and patients with diabetic nephropathy and ESRD.\"\n", " is_usable = validate_and_save_cohort_info(\n", " is_final=True,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=is_gene_available,\n", " is_trait_available=is_trait_available,\n", " is_biased=is_biased,\n", " df=linked_data,\n", " note=note\n", " )\n", " \n", " # 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.to_csv(out_data_file)\n", " print(f\"Linked data saved to {out_data_file}\")\n", " else:\n", " print(\"Data not usable for the trait study - not saving final linked data.\")\n", " except Exception as e:\n", " print(f\"Error linking or processing data: {e}\")\n", " validate_and_save_cohort_info(\n", " is_final=True,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=is_gene_available,\n", " is_trait_available=is_trait_available,\n", " is_biased=True, # Assume biased if there's an error\n", " df=pd.DataFrame(), # Empty dataframe for metadata\n", " note=f\"Error in data processing: {str(e)}\"\n", " )\n", "else:\n", " # We can't proceed with linking if either trait or gene data is missing\n", " print(\"Cannot proceed with data linking due to missing trait or gene data.\")\n", " validate_and_save_cohort_info(\n", " is_final=True,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=is_gene_available,\n", " is_trait_available=is_trait_available,\n", " is_biased=True, # Data is unusable if we're missing components\n", " df=pd.DataFrame(), # Empty dataframe for metadata\n", " note=\"Missing essential data components for linking (trait data or gene expression data).\"\n", " )" ] } ], "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 }