{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "64d15c72", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:23:27.001248Z", "iopub.status.busy": "2025-03-25T07:23:27.001132Z", "iopub.status.idle": "2025-03-25T07:23:27.164245Z", "shell.execute_reply": "2025-03-25T07:23:27.163791Z" } }, "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 = \"Kidney_stones\"\n", "cohort = \"GSE73680\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Kidney_stones\"\n", "in_cohort_dir = \"../../input/GEO/Kidney_stones/GSE73680\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Kidney_stones/GSE73680.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Kidney_stones/gene_data/GSE73680.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Kidney_stones/clinical_data/GSE73680.csv\"\n", "json_path = \"../../output/preprocess/Kidney_stones/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "99019a7c", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "ffb1f96d", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:23:27.165572Z", "iopub.status.busy": "2025-03-25T07:23:27.165422Z", "iopub.status.idle": "2025-03-25T07:23:27.360558Z", "shell.execute_reply": "2025-03-25T07:23:27.359978Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Gene expression profile of Randall's Plaque tissue\"\n", "!Series_summary\t\"Randall’s plaque (RP) is the origin of renal calcification on which idiopathic calcium oxalate (CaOx) kidney stones develop. To establish genomic pathogenesis of RP, we performed the microarray analysis for comparing the gene expressions among renal papillary RP and normal tissue of 23 CaOx and 6 calcium phosphate (CaP) stone formers, and normal papillary tissue of 7 control patients. Compare to normal papillary tissue, RP tissue contained up-regulation of lipocalin 2, interleukin 11, prostaglandin-endoperoxide synthase 1, glutathione peroxidase 3, and monocyte to macrophage differentiation, whereas down-regulation of solute carrier family 12 member 1 and sodium leak channel non selective (either > 2.0- or 0.5-fold, p <0.01). The network and toxicity analysis showed these genes had association with activated mitogen-activated protein kinase, Akt/ phosphatidylinositol 3-kinase pathway, and pro-inflammatory cytokines, which caused renal injury and oxidative stress.\"\n", "!Series_overall_design\t\"Human renal papillary tip tissues were biopsied during endoscopic kidney stone surgery. Tissues including Randall's Plaque from calcium stone former was designed as P group, normal papillary tissue from calcium stone former was designed as N group, and normal papillary tissue from control patients without any kidney stone was designed as C group. Comparison among P, N, and C group was performed.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['gender: female', 'gender: male'], 1: ['lesion: Normal mucosa', 'lesion: Plaque mucosa'], 2: ['tissue type: normal papillary tissue from control patients without any kidney stone', 'tissue type: normal papillary tissue from calcium stone', \"tissue type: Randall's Plaque from calcium stone\"]}\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": "d6c9e818", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "94587435", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:23:27.362335Z", "iopub.status.busy": "2025-03-25T07:23:27.362207Z", "iopub.status.idle": "2025-03-25T07:23:27.373580Z", "shell.execute_reply": "2025-03-25T07:23:27.373110Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Preview of extracted clinical features:\n", "{'GSM1900673': [0.0, 0.0], 'GSM1900674': [0.0, 1.0], 'GSM1900675': [0.0, 0.0], 'GSM1900676': [1.0, 0.0], 'GSM1900677': [0.0, 1.0], 'GSM1900678': [1.0, 1.0], 'GSM1900679': [0.0, 1.0], 'GSM1900680': [1.0, 1.0], 'GSM1900681': [1.0, 1.0], 'GSM1900682': [0.0, 1.0], 'GSM1900683': [1.0, 1.0], 'GSM1900684': [0.0, 0.0], 'GSM1900685': [0.0, 1.0], 'GSM1900686': [0.0, 0.0], 'GSM1900687': [1.0, 0.0], 'GSM1900688': [0.0, 1.0], 'GSM1900689': [1.0, 1.0], 'GSM1900690': [0.0, 1.0], 'GSM1900691': [1.0, 1.0], 'GSM1900692': [0.0, 1.0], 'GSM1900693': [1.0, 1.0], 'GSM1900694': [0.0, 1.0], 'GSM1900695': [1.0, 1.0], 'GSM1900696': [0.0, 1.0], 'GSM1900697': [1.0, 1.0], 'GSM1900698': [0.0, 1.0], 'GSM1900699': [1.0, 1.0], 'GSM1900700': [0.0, 1.0], 'GSM1900701': [1.0, 1.0], 'GSM1900702': [0.0, 0.0], 'GSM1900703': [0.0, 1.0], 'GSM1900704': [1.0, 1.0], 'GSM1900705': [0.0, 1.0], 'GSM1900706': [1.0, 1.0], 'GSM1900707': [0.0, 0.0], 'GSM1900708': [1.0, 0.0], 'GSM1900709': [1.0, 1.0], 'GSM1900710': [0.0, 1.0], 'GSM1900711': [1.0, 1.0], 'GSM1900712': [1.0, 1.0], 'GSM1900713': [0.0, 1.0], 'GSM1900714': [0.0, 1.0], 'GSM1900715': [1.0, 1.0], 'GSM1900716': [0.0, 0.0], 'GSM1900717': [1.0, 0.0], 'GSM1900718': [0.0, 0.0], 'GSM1900719': [1.0, 0.0], 'GSM1900720': [0.0, 1.0], 'GSM1900721': [1.0, 1.0], 'GSM1900722': [0.0, 0.0], 'GSM1900723': [1.0, 0.0], 'GSM1900724': [0.0, 0.0], 'GSM1900725': [1.0, 0.0], 'GSM1900726': [0.0, 1.0], 'GSM1900727': [1.0, 1.0], 'GSM1900728': [0.0, 0.0], 'GSM1900729': [1.0, 0.0], 'GSM1900730': [0.0, 0.0], 'GSM1900731': [1.0, 0.0], 'GSM1900732': [0.0, 0.0], 'GSM1900733': [0.0, 1.0], 'GSM1900734': [1.0, 1.0]}\n", "Clinical data saved to: ../../output/preprocess/Kidney_stones/clinical_data/GSE73680.csv\n" ] } ], "source": [ "# 1. Check gene expression data availability\n", "# Based on background information, this dataset contains gene expression data from microarray analysis\n", "is_gene_available = True\n", "\n", "# 2. Variable availability and data type conversion\n", "# 2.1 Data Availability\n", "# Looking at the Sample Characteristics Dictionary\n", "# trait_row: We can infer the trait (kidney stones) from the lesion or tissue type information\n", "trait_row = 1 # 'lesion' seems to indicate presence of Randall's Plaque\n", "age_row = None # Age information is not available in the sample characteristics\n", "gender_row = 0 # Gender information is available\n", "\n", "# 2.2 Data Type Conversion functions\n", "def convert_trait(value):\n", " \"\"\"Convert trait information to binary value (0: no kidney stones, 1: kidney stones)\"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract the value after colon if present\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Convert based on lesion type\n", " if 'Plaque' in value:\n", " return 1 # Randall's Plaque present (kidney stone)\n", " elif 'Normal' in value:\n", " return 0 # Normal mucosa (no kidney stone)\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age information (not used as age is not available)\"\"\"\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender information to binary (0: female, 1: male)\"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract the value after colon if present\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Convert gender to binary\n", " if value.lower() == 'female':\n", " return 0\n", " elif value.lower() == 'male':\n", " return 1\n", " else:\n", " return None\n", "\n", "# 3. Save metadata\n", "# Determine trait data availability\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 (if trait data is available)\n", "if trait_row is not None:\n", " # We need to use the clinical_data that should have been loaded previously\n", " # and not try to recreate it from the sample characteristics dictionary\n", " \n", " # Check if clinical data exists from previous steps\n", " try:\n", " # Assuming clinical_data is available from previous steps\n", " # Extract clinical features\n", " selected_clinical_df = geo_select_clinical_features(\n", " clinical_df=clinical_data,\n", " trait=trait,\n", " trait_row=trait_row,\n", " convert_trait=convert_trait,\n", " age_row=age_row,\n", " convert_age=convert_age,\n", " gender_row=gender_row,\n", " convert_gender=convert_gender\n", " )\n", " \n", " # Preview the extracted clinical features\n", " print(\"Preview of extracted clinical features:\")\n", " print(preview_df(selected_clinical_df))\n", " \n", " # Save to CSV\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", " print(f\"Clinical data saved to: {out_clinical_data_file}\")\n", " except NameError:\n", " print(\"Clinical data not found. Make sure it was loaded in a previous step.\")\n", " except Exception as e:\n", " print(f\"Error processing clinical data: {e}\")\n" ] }, { "cell_type": "markdown", "id": "692b1221", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "0a993504", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:23:27.375249Z", "iopub.status.busy": "2025-03-25T07:23:27.375131Z", "iopub.status.idle": "2025-03-25T07:23:27.757564Z", "shell.execute_reply": "2025-03-25T07:23:27.757024Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Matrix file found: ../../input/GEO/Kidney_stones/GSE73680/GSE73680_series_matrix.txt.gz\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape: (50739, 62)\n", "First 20 gene/probe identifiers:\n", "Index(['(+)E1A_r60_1', '(+)E1A_r60_3', '(+)E1A_r60_a104', '(+)E1A_r60_a107',\n", " '(+)E1A_r60_a135', '(+)E1A_r60_a20', '(+)E1A_r60_a22', '(+)E1A_r60_a97',\n", " '(+)E1A_r60_n11', '(+)E1A_r60_n9', '3xSLv1', 'A_19_P00315452',\n", " 'A_19_P00315459', 'A_19_P00315482', 'A_19_P00315492', 'A_19_P00315493',\n", " 'A_19_P00315502', 'A_19_P00315506', 'A_19_P00315518', 'A_19_P00315519'],\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": "037b2e12", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "88a686f7", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:23:27.759076Z", "iopub.status.busy": "2025-03-25T07:23:27.758934Z", "iopub.status.idle": "2025-03-25T07:23:27.761125Z", "shell.execute_reply": "2025-03-25T07:23:27.760753Z" } }, "outputs": [], "source": [ "# Looking at the gene identifiers, they appear to be Agilent microarray probe IDs\n", "# rather than standard human gene symbols. They follow the format A_19_P00315452, etc.\n", "# which is typical for Agilent microarray platforms. These will need to be mapped\n", "# to human gene symbols for meaningful analysis.\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "43347947", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "65bb8cde", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:23:27.762467Z", "iopub.status.busy": "2025-03-25T07:23:27.762355Z", "iopub.status.idle": "2025-03-25T07:23:33.496344Z", "shell.execute_reply": "2025-03-25T07:23:33.495657Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene annotation preview:\n", "Columns in gene annotation: ['ID', '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': ['GE_BrightCorner', 'DarkCorner', 'A_23_P117082', 'A_33_P3246448', 'A_33_P3318220'], 'SPOT_ID': ['CONTROL', 'CONTROL', 'A_23_P117082', 'A_33_P3246448', 'A_33_P3318220'], 'CONTROL_TYPE': ['pos', 'pos', 'FALSE', 'FALSE', 'FALSE'], 'REFSEQ': [nan, nan, 'NM_015987', 'NM_080671', 'NM_178466'], 'GB_ACC': [nan, nan, 'NM_015987', 'NM_080671', 'NM_178466'], 'LOCUSLINK_ID': [nan, nan, 50865.0, 23704.0, 128861.0], 'GENE_SYMBOL': [nan, nan, 'HEBP1', 'KCNE4', 'BPIFA3'], 'GENE_NAME': [nan, nan, 'heme binding protein 1', 'potassium voltage-gated channel, Isk-related family, member 4', 'BPI fold containing family A, member 3'], 'UNIGENE_ID': [nan, nan, 'Hs.642618', 'Hs.348522', 'Hs.360989'], 'ENSEMBL_ID': [nan, nan, 'ENST00000014930', 'ENST00000281830', 'ENST00000375454'], 'ACCESSION_STRING': [nan, nan, 'ref|NM_015987|ens|ENST00000014930|gb|AF117615|gb|BC016277', 'ref|NM_080671|ens|ENST00000281830|tc|THC2655788', 'ref|NM_178466|ens|ENST00000375454|ens|ENST00000471233|tc|THC2478474'], 'CHROMOSOMAL_LOCATION': [nan, nan, 'chr12:13127906-13127847', 'chr2:223920197-223920256', 'chr20:31812208-31812267'], 'CYTOBAND': [nan, nan, 'hs|12p13.1', 'hs|2q36.1', 'hs|20q11.21'], 'DESCRIPTION': [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]', 'Homo sapiens BPI fold containing family A, member 3 (BPIFA3), transcript variant 1, mRNA [NM_178466]'], 'GO_ID': [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)', 'GO:0005576(extracellular region)|GO:0008289(lipid binding)'], 'SEQUENCE': [nan, nan, 'AAGGGGGAAAATGTGATTTGTGCCTGATCTTTCATCTGTGATTCTTATAAGAGCTTTGTC', 'GCAAGTCTCTCTGCACCTATTAAAAAGTGATGTATATACTTCCTTCTTATTCTGTTGAGT', 'CATTCCATAAGGAGTGGTTCTCGGCAAATATCTCACTTGAATTTGACCTTGAATTGAGAC']}\n", "\n", "Analyzing gene symbol related columns:\n", "Sample GENE_SYMBOL values: ['HEBP1', 'KCNE4', 'BPIFA3', 'LOC100129869', 'IRG1']\n", "\n", "Gene data first ID: (+)E1A_r60_1\n", "\n", "Analyzing potential probe ID columns:\n", "Sample ID values: ['GE_BrightCorner', 'DarkCorner', 'A_23_P117082', 'A_33_P3246448', 'A_33_P3318220']\n", "Sample SPOT_ID values: ['CONTROL', 'CONTROL', 'A_23_P117082', 'A_33_P3246448', 'A_33_P3318220']\n", "\n", "Checking for overlap between gene data IDs and annotation:\n", "Number of IDs that match between gene data and annotation 'ID' column: 16\n", "Sample overlapping IDs: ['3xSLv1', 'A_19_P00319311', '(+)E1A_r60_a107', 'A_19_P00319765', 'A_19_P00322002']\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", "# Check for gene information in the gene annotation columns\n", "print(\"\\nAnalyzing gene symbol related columns:\")\n", "if 'GENE_SYMBOL' in gene_annotation.columns:\n", " print(f\"Sample GENE_SYMBOL values: {gene_annotation['GENE_SYMBOL'].dropna().head(5).tolist()}\")\n", "\n", "# Try to find the probe IDs in the gene annotation\n", "gene_data_id_prefix = gene_data.index[0]\n", "print(f\"\\nGene data first ID: {gene_data_id_prefix}\")\n", "\n", "# Look for columns that might contain probe IDs\n", "print(\"\\nAnalyzing potential probe ID columns:\")\n", "if 'ID' in gene_annotation.columns:\n", " print(f\"Sample ID values: {gene_annotation['ID'].head(5).tolist()}\")\n", " \n", "if 'SPOT_ID' in gene_annotation.columns:\n", " print(f\"Sample SPOT_ID values: {gene_annotation['SPOT_ID'].head(5).tolist()}\")\n", "\n", "# Check if there's any match between gene data index and annotation IDs\n", "print(\"\\nChecking for overlap between gene data IDs and annotation:\")\n", "gene_data_ids = set(gene_data.index[:1000]) # Get a sample of gene data IDs\n", "annotation_ids = set(gene_annotation['ID'].astype(str)[:1000])\n", "overlap = gene_data_ids.intersection(annotation_ids)\n", "print(f\"Number of IDs that match between gene data and annotation 'ID' column: {len(overlap)}\")\n", "print(f\"Sample overlapping IDs: {list(overlap)[:5] if overlap else 'None'}\")\n" ] }, { "cell_type": "markdown", "id": "c6342081", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "dd733e29", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:23:33.498212Z", "iopub.status.busy": "2025-03-25T07:23:33.498076Z", "iopub.status.idle": "2025-03-25T07:23:34.546470Z", "shell.execute_reply": "2025-03-25T07:23:34.545802Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene mapping dataframe shape: (46204, 2)\n", "Preview of gene mapping dataframe:\n", " ID Gene\n", "2 A_23_P117082 HEBP1\n", "3 A_33_P3246448 KCNE4\n", "4 A_33_P3318220 BPIFA3\n", "5 A_33_P3236322 LOC100129869\n", "6 A_33_P3319925 IRG1\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression dataframe shape after mapping: (20353, 62)\n", "Preview of gene expression dataframe (first 5 genes, first 5 samples):\n", " GSM1900673 GSM1900674 GSM1900675 GSM1900676 GSM1900677\n", "Gene \n", "A1BG -1.082109 -2.449026 -1.054509 -0.551611 -3.563693\n", "A1BG-AS1 0.194566 0.426283 0.711320 0.702709 -0.451157\n", "A1CF -0.782465 -1.308139 -0.578092 0.341932 -0.704205\n", "A2LD1 -0.567108 -0.713197 1.067966 1.425751 -1.585089\n", "A2M 1.057854 0.512311 0.077415 1.521002 -0.386456\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data saved to: ../../output/preprocess/Kidney_stones/gene_data/GSE73680.csv\n" ] } ], "source": [ "# 1. Identify which columns in the gene annotation dataframe contain gene IDs and gene symbols\n", "# From the previous output, we can see that:\n", "# - The ID column in gene_annotation contains probe identifiers (e.g., A_23_P117082)\n", "# - The GENE_SYMBOL column contains gene symbols (e.g., HEBP1, KCNE4)\n", "# - There is some overlap between gene_data index and gene_annotation ID column\n", "\n", "# 2. Extract the gene ID and gene symbol columns to create a mapping dataframe\n", "mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='GENE_SYMBOL')\n", "print(f\"Gene mapping dataframe shape: {mapping_df.shape}\")\n", "print(\"Preview of gene 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\"Gene expression dataframe shape after mapping: {gene_data.shape}\")\n", "print(\"Preview of gene expression dataframe (first 5 genes, first 5 samples):\")\n", "print(gene_data.iloc[:5, :5])\n", "\n", "# Save the gene expression data to a 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": "5db4bd72", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "f6241a22", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:23:34.548684Z", "iopub.status.busy": "2025-03-25T07:23:34.548287Z", "iopub.status.idle": "2025-03-25T07:23:46.029414Z", "shell.execute_reply": "2025-03-25T07:23:46.028755Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape before normalization: (20353, 62)\n", "Gene data shape after normalization: (19847, 62)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene expression data saved to ../../output/preprocess/Kidney_stones/gene_data/GSE73680.csv\n", "Original clinical data preview:\n", " !Sample_geo_accession \\\n", "0 !Sample_characteristics_ch1 \n", "1 !Sample_characteristics_ch1 \n", "2 !Sample_characteristics_ch1 \n", "\n", " GSM1900673 \\\n", "0 gender: female \n", "1 lesion: Normal mucosa \n", "2 tissue type: normal papillary tissue from cont... \n", "\n", " GSM1900674 \\\n", "0 gender: male \n", "1 lesion: Normal mucosa \n", "2 tissue type: normal papillary tissue from cont... \n", "\n", " GSM1900675 \\\n", "0 gender: female \n", "1 lesion: Normal mucosa \n", "2 tissue type: normal papillary tissue from calc... \n", "\n", " GSM1900676 \\\n", "0 gender: female \n", "1 lesion: Plaque mucosa \n", "2 tissue type: Randall's Plaque from calcium stone \n", "\n", " GSM1900677 \\\n", "0 gender: male \n", "1 lesion: Normal mucosa \n", "2 tissue type: normal papillary tissue from calc... \n", "\n", " GSM1900678 \\\n", "0 gender: male \n", "1 lesion: Plaque mucosa \n", "2 tissue type: Randall's Plaque from calcium stone \n", "\n", " GSM1900679 \\\n", "0 gender: male \n", "1 lesion: Normal mucosa \n", "2 tissue type: normal papillary tissue from calc... \n", "\n", " GSM1900680 \\\n", "0 gender: male \n", "1 lesion: Plaque mucosa \n", "2 tissue type: Randall's Plaque from calcium stone \n", "\n", " GSM1900681 ... \\\n", "0 gender: male ... \n", "1 lesion: Plaque mucosa ... \n", "2 tissue type: Randall's Plaque from calcium stone ... \n", "\n", " GSM1900725 \\\n", "0 gender: female \n", "1 lesion: Plaque mucosa \n", "2 tissue type: Randall's Plaque from calcium stone \n", "\n", " GSM1900726 \\\n", "0 gender: male \n", "1 lesion: Normal mucosa \n", "2 tissue type: normal papillary tissue from calc... \n", "\n", " GSM1900727 \\\n", "0 gender: male \n", "1 lesion: Plaque mucosa \n", "2 tissue type: Randall's Plaque from calcium stone \n", "\n", " GSM1900728 \\\n", "0 gender: female \n", "1 lesion: Normal mucosa \n", "2 tissue type: normal papillary tissue from calc... \n", "\n", " GSM1900729 \\\n", "0 gender: female \n", "1 lesion: Plaque mucosa \n", "2 tissue type: Randall's Plaque from calcium stone \n", "\n", " GSM1900730 \\\n", "0 gender: female \n", "1 lesion: Normal mucosa \n", "2 tissue type: normal papillary tissue from calc... \n", "\n", " GSM1900731 \\\n", "0 gender: female \n", "1 lesion: Plaque mucosa \n", "2 tissue type: Randall's Plaque from calcium stone \n", "\n", " GSM1900732 \\\n", "0 gender: female \n", "1 lesion: Normal mucosa \n", "2 tissue type: normal papillary tissue from cont... \n", "\n", " GSM1900733 \\\n", "0 gender: male \n", "1 lesion: Normal mucosa \n", "2 tissue type: normal papillary tissue from calc... \n", "\n", " GSM1900734 \n", "0 gender: male \n", "1 lesion: Plaque mucosa \n", "2 tissue type: Randall's Plaque from calcium stone \n", "\n", "[3 rows x 63 columns]\n", "Selected clinical data shape: (2, 62)\n", "Clinical data preview:\n", " GSM1900673 GSM1900674 GSM1900675 GSM1900676 GSM1900677 \\\n", "Kidney_stones 0.0 0.0 0.0 1.0 0.0 \n", "Gender 0.0 1.0 0.0 0.0 1.0 \n", "\n", " GSM1900678 GSM1900679 GSM1900680 GSM1900681 GSM1900682 \\\n", "Kidney_stones 1.0 0.0 1.0 1.0 0.0 \n", "Gender 1.0 1.0 1.0 1.0 1.0 \n", "\n", " ... GSM1900725 GSM1900726 GSM1900727 GSM1900728 \\\n", "Kidney_stones ... 1.0 0.0 1.0 0.0 \n", "Gender ... 0.0 1.0 1.0 0.0 \n", "\n", " GSM1900729 GSM1900730 GSM1900731 GSM1900732 GSM1900733 \\\n", "Kidney_stones 1.0 0.0 1.0 0.0 0.0 \n", "Gender 0.0 0.0 0.0 0.0 1.0 \n", "\n", " GSM1900734 \n", "Kidney_stones 1.0 \n", "Gender 1.0 \n", "\n", "[2 rows x 62 columns]\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data shape before processing: (62, 19849)\n", "Linked data preview (first 5 rows, 5 columns):\n", " Kidney_stones Gender A1BG A1BG-AS1 A1CF\n", "GSM1900673 0.0 0.0 -1.082109 0.194566 -0.782465\n", "GSM1900674 0.0 1.0 -2.449026 0.426283 -1.308139\n", "GSM1900675 0.0 0.0 -1.054509 0.711320 -0.578092\n", "GSM1900676 1.0 0.0 -0.551611 0.702709 0.341932\n", "GSM1900677 0.0 1.0 -3.563693 -0.451157 -0.704205\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Data shape after handling missing values: (62, 19849)\n", "For the feature 'Kidney_stones', the least common label is '1.0' with 29 occurrences. This represents 46.77% of the dataset.\n", "For the feature 'Gender', the least common label is '0.0' with 22 occurrences. This represents 35.48% of the dataset.\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data saved to ../../output/preprocess/Kidney_stones/GSE73680.csv\n" ] } ], "source": [ "# 1. Normalize gene symbols in the gene expression data\n", "# Use normalize_gene_symbols_in_index to standardize gene symbols\n", "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"Gene data shape before normalization: {gene_data.shape}\")\n", "print(f\"Gene data shape after normalization: {normalized_gene_data.shape}\")\n", "\n", "# Save the normalized gene data to file\n", "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", "normalized_gene_data.to_csv(out_gene_data_file)\n", "print(f\"Normalized gene expression data saved to {out_gene_data_file}\")\n", "\n", "# Load the actual clinical data from the matrix file that was previously obtained in Step 1\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "background_info, clinical_data = get_background_and_clinical_data(matrix_file)\n", "\n", "# Get preview of clinical data to understand its structure\n", "print(\"Original clinical data preview:\")\n", "print(clinical_data.head())\n", "\n", "# 2. If we have trait data available, proceed with linking\n", "if trait_row is not None:\n", " # Extract clinical features using the original clinical data\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", " print(f\"Selected clinical data shape: {selected_clinical_df.shape}\")\n", " print(\"Clinical data preview:\")\n", " print(selected_clinical_df.head())\n", "\n", " # Link the clinical and genetic data\n", " linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)\n", " print(f\"Linked data shape before processing: {linked_data.shape}\")\n", " print(\"Linked data preview (first 5 rows, 5 columns):\")\n", " print(linked_data.iloc[:5, :5] if not linked_data.empty else \"Empty dataframe\")\n", "\n", " # 3. Handle missing values\n", " try:\n", " linked_data = handle_missing_values(linked_data, trait)\n", " print(f\"Data shape after handling missing values: {linked_data.shape}\")\n", " except Exception as e:\n", " print(f\"Error handling missing values: {e}\")\n", " linked_data = pd.DataFrame() # Create empty dataframe if error occurs\n", "\n", " # 4. Check for bias in features\n", " if not linked_data.empty and linked_data.shape[0] > 0:\n", " # Check if trait is biased\n", " trait_type = 'binary' if len(linked_data[trait].unique()) <= 2 else 'continuous'\n", " if trait_type == \"binary\":\n", " is_biased = judge_binary_variable_biased(linked_data, trait)\n", " else:\n", " is_biased = judge_continuous_variable_biased(linked_data, trait)\n", " \n", " # Remove biased demographic features\n", " if \"Age\" in linked_data.columns:\n", " age_biased = judge_continuous_variable_biased(linked_data, 'Age')\n", " if age_biased:\n", " linked_data = linked_data.drop(columns='Age')\n", " \n", " if \"Gender\" in linked_data.columns:\n", " gender_biased = judge_binary_variable_biased(linked_data, 'Gender')\n", " if gender_biased:\n", " linked_data = linked_data.drop(columns='Gender')\n", " else:\n", " is_biased = True\n", " print(\"Cannot check for bias as dataframe is empty or has no rows after missing value handling\")\n", "\n", " # 5. Validate and save cohort information\n", " note = \"\"\n", " if linked_data.empty or linked_data.shape[0] == 0:\n", " note = \"Dataset contains gene expression data related to Randall's plaque tissue, but linking clinical and genetic data failed, possibly due to mismatched sample IDs.\"\n", " else:\n", " note = \"Dataset contains gene expression data from Randall's plaque tissue associated with kidney stones.\"\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=True,\n", " is_biased=is_biased,\n", " df=linked_data,\n", " note=note\n", " )\n", "\n", " # 6. Save the linked data if 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(\"Dataset is not usable for analysis. No linked data file saved.\")\n", "else:\n", " # If no trait data available, validate with trait_available=False\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,\n", " is_biased=True, # Set to True since we can't use data without trait\n", " df=pd.DataFrame(), # Empty DataFrame\n", " note=\"Dataset contains gene expression data but lacks proper clinical trait information for kidney stones analysis.\"\n", " )\n", " \n", " print(\"Dataset is not usable for kidney stones analysis due to lack of clinical trait data. No linked data file 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 }