{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "700cb6c1", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:18:13.809457Z", "iopub.status.busy": "2025-03-25T08:18:13.809234Z", "iopub.status.idle": "2025-03-25T08:18:13.979955Z", "shell.execute_reply": "2025-03-25T08:18:13.979624Z" } }, "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 = \"GSE180393\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Chronic_kidney_disease\"\n", "in_cohort_dir = \"../../input/GEO/Chronic_kidney_disease/GSE180393\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Chronic_kidney_disease/GSE180393.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Chronic_kidney_disease/gene_data/GSE180393.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Chronic_kidney_disease/clinical_data/GSE180393.csv\"\n", "json_path = \"../../output/preprocess/Chronic_kidney_disease/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "a8468b30", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "f6655a78", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:18:13.981448Z", "iopub.status.busy": "2025-03-25T08:18:13.981297Z", "iopub.status.idle": "2025-03-25T08:18:14.102277Z", "shell.execute_reply": "2025-03-25T08:18:14.101911Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Glomerular Transcriptome in the Cprobe Cohort\"\n", "!Series_summary\t\"We used microarrays to analyze the transcriptome of microdissected renal biopsies from patients with kidney disease and living donors. We derived pathway specific scores for Angiopoietin-Tie signaling pathway activation at mRNA level (or transcriptome level) for individual patients and studied the association of pathway activation with disease outcomes.\"\n", "!Series_overall_design\t\"Glomerular gene expression data from micro-dissected human kidney biopsy samples  from patients with chronic kidney disease(Lupus, DN, IgA,HT, TN) and healthy living donors. Profiling was performed on Affymetrix ST2.1 microarray platform. \"\n", "Sample Characteristics Dictionary:\n", "{0: ['sample group: Living donor', 'sample group: infection-associated GN', 'sample group: FSGS', 'sample group: LN-WHO III', 'sample group: LN-WHO IV', 'sample group: DN', 'sample group: amyloidosis', 'sample group: Membrano-Proliferative GN', 'sample group: MN', 'sample group: AKI', 'sample group: LN-WHO V', 'sample group: FGGS', \"sample group: 2'FSGS\", 'sample group: Thin-BMD', 'sample group: Immuncomplex GN', 'sample group: LN-WHO-V', 'sample group: IgAN', 'sample group: LN-WHO IV+V', 'sample group: LN-WHO III+V', 'sample group: LN-WHO-I/II', 'sample group: chronic Glomerulonephritis (GN) with infiltration by CLL', 'sample group: CKD with mod-severe Interstitial fibrosis', 'sample group: Fibrillary GN', 'sample group: Interstitial nephritis', 'sample group: Hypertensive Nephrosclerosis', 'sample group: Unaffected parts of Tumor Nephrectomy'], 1: ['tissue: Glomeruli from kidney biopsy']}\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": "628f8a7d", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "ae886cd5", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:18:14.103702Z", "iopub.status.busy": "2025-03-25T08:18:14.103579Z", "iopub.status.idle": "2025-03-25T08:18:14.111960Z", "shell.execute_reply": "2025-03-25T08:18:14.111653Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Preview of selected clinical features:\n", "{0: [0.0]}\n", "Clinical data saved to ../../output/preprocess/Chronic_kidney_disease/clinical_data/GSE180393.csv\n" ] } ], "source": [ "import pandas as pd\n", "import os\n", "from typing import Optional, Callable, Dict, Any\n", "import json\n", "import numpy as np\n", "\n", "# 1. Gene Expression Data Availability\n", "# Based on the background info, this dataset contains glomerular gene expression data from\n", "# microarrays (Affymetrix ST2.1 platform), so it's suitable for our analysis\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "# From sample characteristics, we can see information about the disease status in row 0\n", "trait_row = 0\n", "# Age and gender are not explicitly mentioned in the sample characteristics\n", "age_row = None\n", "gender_row = None\n", "\n", "# 2.2 Data Type Conversion\n", "def convert_trait(value: str) -> int:\n", " \"\"\"\n", " Convert the disease status to binary where:\n", " 0 = Control/Healthy (Living donor)\n", " 1 = CKD (any other condition)\n", " \"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract the value after the colon if present\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Living donors are controls, all other conditions represent CKD\n", " if 'Living donor' in value:\n", " return 0\n", " else:\n", " return 1\n", "\n", "def convert_age(value: str) -> Optional[float]:\n", " \"\"\"\n", " Convert age value to float.\n", " Not used in this dataset as age information is not available.\n", " \"\"\"\n", " return None\n", "\n", "def convert_gender(value: str) -> Optional[int]:\n", " \"\"\"\n", " Convert gender to binary where:\n", " 0 = Female\n", " 1 = Male\n", " Not used in this dataset as gender information is not available.\n", " \"\"\"\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", "# Save the initial filtering information\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", " # Try to find the clinical data file\n", " clinical_data_path = os.path.join(in_cohort_dir, \"clinical_data.csv\")\n", " sample_char_path = os.path.join(in_cohort_dir, \"sample_characteristics.txt\")\n", " \n", " if os.path.exists(clinical_data_path):\n", " # If clinical_data.csv exists, read it directly\n", " clinical_data = pd.read_csv(clinical_data_path)\n", " elif os.path.exists(sample_char_path):\n", " # If sample_characteristics.txt exists, read it\n", " clinical_data = pd.read_csv(sample_char_path, sep='\\t', index_col=0)\n", " else:\n", " # If neither file exists, create a dataframe from the sample characteristics dictionary\n", " # that was shown in the previous output\n", " \n", " # Sample values from the dictionary\n", " sample_groups = [\n", " 'sample group: Living donor', \n", " 'sample group: infection-associated GN',\n", " 'sample group: FSGS',\n", " 'sample group: LN-WHO III',\n", " 'sample group: LN-WHO IV',\n", " 'sample group: DN',\n", " 'sample group: amyloidosis',\n", " 'sample group: Membrano-Proliferative GN',\n", " 'sample group: MN',\n", " 'sample group: AKI',\n", " 'sample group: LN-WHO V',\n", " 'sample group: FGGS',\n", " \"sample group: 2'FSGS\",\n", " 'sample group: Thin-BMD',\n", " 'sample group: Immuncomplex GN',\n", " 'sample group: LN-WHO-V',\n", " 'sample group: IgAN',\n", " 'sample group: LN-WHO IV+V',\n", " 'sample group: LN-WHO III+V',\n", " 'sample group: LN-WHO-I/II',\n", " 'sample group: chronic Glomerulonephritis (GN) with infiltration by CLL',\n", " 'sample group: CKD with mod-severe Interstitial fibrosis',\n", " 'sample group: Fibrillary GN',\n", " 'sample group: Interstitial nephritis',\n", " 'sample group: Hypertensive Nephrosclerosis',\n", " 'sample group: Unaffected parts of Tumor Nephrectomy'\n", " ]\n", " \n", " # Create sample IDs (we don't have real IDs, so we'll use placeholders)\n", " sample_ids = [f\"GSM{i+1}\" for i in range(len(sample_groups))]\n", " \n", " # Create a DataFrame with rows for each sample and a column for the trait\n", " data = {\n", " 0: sample_groups # Using key 0 for 'sample group' as in the original dictionary\n", " }\n", " \n", " # Create the clinical data DataFrame with appropriate index\n", " clinical_data = pd.DataFrame(data, index=sample_ids)\n", " \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 DataFrame\n", " preview = preview_df(selected_clinical_df)\n", " print(\"Preview of selected clinical features:\")\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", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "18ab212c", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "e084730a", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:18:14.113185Z", "iopub.status.busy": "2025-03-25T08:18:14.113075Z", "iopub.status.idle": "2025-03-25T08:18:14.303034Z", "shell.execute_reply": "2025-03-25T08:18:14.302633Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "SOFT file: ../../input/GEO/Chronic_kidney_disease/GSE180393/GSE180393_family.soft.gz\n", "Matrix file: ../../input/GEO/Chronic_kidney_disease/GSE180393/GSE180393_series_matrix.txt.gz\n", "Gene data shape: (25582, 62)\n", "First 20 gene/probe identifiers:\n", "['100009613_at', '100009676_at', '10000_at', '10001_at', '10002_at', '100033413_at', '100033422_at', '100033423_at', '100033424_at', '100033425_at', '100033426_at', '100033427_at', '100033428_at', '100033430_at', '100033431_at', '100033432_at', '100033434_at', '100033435_at', '100033436_at', '100033437_at']\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": "408c9055", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "d09197ab", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:18:14.304302Z", "iopub.status.busy": "2025-03-25T08:18:14.304179Z", "iopub.status.idle": "2025-03-25T08:18:14.306209Z", "shell.execute_reply": "2025-03-25T08:18:14.305910Z" } }, "outputs": [], "source": [ "# Based on the gene identifiers shown, these appear to be Affymetrix Mouse probe IDs \n", "# rather than standard human gene symbols. The format \"number_at\" is characteristic\n", "# of Affymetrix arrays, and the presence of \"at\" suffix indicates this is likely \n", "# mouse data (Mouse430_2 array).\n", "#\n", "# These identifiers need to be mapped to standard gene symbols for analysis.\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "564f129f", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "d391b1df", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:18:14.307374Z", "iopub.status.busy": "2025-03-25T08:18:14.307263Z", "iopub.status.idle": "2025-03-25T08:18:16.091959Z", "shell.execute_reply": "2025-03-25T08:18:16.091564Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene annotation preview:\n", "Columns in gene annotation: ['ID', 'ENTREZ_GENE_ID']\n", "{'ID': ['1_at', '10_at', '100_at', '1000_at', '10000_at'], 'ENTREZ_GENE_ID': ['1', '10', '100', '1000', '10000']}\n", "\n", "Complete sample of a few rows:\n", " ID ENTREZ_GENE_ID\n", "0 1_at 1\n", "1 10_at 10\n", "2 100_at 100\n", "\n", "Potential gene-related columns: ['ID', 'ENTREZ_GENE_ID']\n", "\n", "No direct gene symbol column found. Will use Entrez Gene IDs for mapping.\n", "\n", "Sample mappings from 'ID' to 'ENTREZ_GENE_ID':\n", " ID ENTREZ_GENE_ID\n", "0 1_at 1\n", "1 10_at 10\n", "2 100_at 100\n", "3 1000_at 1000\n", "4 10000_at 10000\n", "5 100009613_at 100009613\n", "6 100009676_at 100009676\n", "7 10001_at 10001\n", "8 10002_at 10002\n", "9 10003_at 10003\n", "\n", "Number of probes with gene ID mappings: 1611728\n", "Sample of valid mappings:\n", " ID ENTREZ_GENE_ID\n", "0 1_at 1\n", "1 10_at 10\n", "2 100_at 100\n", "3 1000_at 1000\n", "4 10000_at 10000\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": "a50090d3", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "69d0e08e", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:18:16.093443Z", "iopub.status.busy": "2025-03-25T08:18:16.093278Z", "iopub.status.idle": "2025-03-25T08:18:19.228085Z", "shell.execute_reply": "2025-03-25T08:18:19.227680Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Mapping data shape: (1611728, 2)\n", "First few rows of mapping data:\n", " ID Gene\n", "0 1_at 1\n", "1 10_at 10\n", "2 100_at 100\n", "3 1000_at 1000\n", "4 10000_at 10000\n", "Number of probes in gene_data: 25582\n", "Number of probes in mapping_data: 25583\n", "Number of common probes: 25582\n", "Sample probe IDs from gene_data:\n", "['100009613_at', '100009676_at', '10000_at', '10001_at', '10002_at']\n", "Sample probe IDs from mapping_data:\n", "['1_at', '10_at', '100_at', '1000_at', '10000_at']\n", "Number of matched probes after filtering: 1611666\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data shape after mapping: (0, 62)\n", "First few gene symbols after mapping:\n", "[]\n", "Gene expression data saved to ../../output/preprocess/Chronic_kidney_disease/gene_data/GSE180393.csv\n" ] } ], "source": [ "# Import necessary modules\n", "import numpy as np\n", "import pandas as pd\n", "import os\n", "\n", "# 1. Identify the appropriate keys for mapping in the gene annotation data\n", "gene_id_col = 'ID' # Column in gene_annotation for probe IDs\n", "gene_symbol_col = 'ENTREZ_GENE_ID' # Column in gene_annotation for gene identifiers\n", "\n", "# 2. Get gene mapping dataframe by extracting the probe IDs and gene symbols\n", "mapping_data = get_gene_mapping(gene_annotation, gene_id_col, gene_symbol_col)\n", "print(f\"Mapping data shape: {mapping_data.shape}\")\n", "print(\"First few rows of mapping data:\")\n", "print(mapping_data.head())\n", "\n", "# We need to check if there's a mismatch between probe IDs in gene_data and mapping_data\n", "gene_data_probes = set(gene_data.index)\n", "mapping_probes = set(mapping_data['ID'])\n", "common_probes = gene_data_probes.intersection(mapping_probes)\n", "print(f\"Number of probes in gene_data: {len(gene_data_probes)}\")\n", "print(f\"Number of probes in mapping_data: {len(mapping_probes)}\")\n", "print(f\"Number of common probes: {len(common_probes)}\")\n", "\n", "# Print sample probes from both datasets\n", "print(\"Sample probe IDs from gene_data:\")\n", "print(list(gene_data.index[:5]))\n", "print(\"Sample probe IDs from mapping_data:\")\n", "print(list(mapping_data['ID'][:5]))\n", "\n", "# For this dataset, we need to use the Entrez gene IDs directly as gene symbols\n", "# Create a modified mapping dataframe that contains only the probes in gene_data\n", "filtered_mapping = mapping_data[mapping_data['ID'].isin(gene_data.index)].copy()\n", "print(f\"Number of matched probes after filtering: {len(filtered_mapping)}\")\n", "\n", "# Check if we have sufficient matches\n", "if len(filtered_mapping) > 0:\n", " # Convert the Entrez IDs to strings to use as gene symbols\n", " filtered_mapping['Gene'] = filtered_mapping['Gene'].astype(str)\n", " \n", " # Apply gene mapping using the filtered mapping data\n", " gene_data = apply_gene_mapping(gene_data, filtered_mapping)\n", " print(f\"Gene expression data shape after mapping: {gene_data.shape}\")\n", " print(\"First few gene symbols after mapping:\")\n", " print(list(gene_data.index[:10]))\n", "else:\n", " print(\"ERROR: No matching probe IDs found between gene expression data and mapping data!\")\n", " # Create an empty dataframe with the same columns as gene_data\n", " gene_data = pd.DataFrame(columns=gene_data.columns)\n", "\n", "# Save the gene data 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": "9e73a495", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "6c22e532", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:18:19.229517Z", "iopub.status.busy": "2025-03-25T08:18:19.229391Z", "iopub.status.idle": "2025-03-25T08:18:19.342644Z", "shell.execute_reply": "2025-03-25T08:18:19.342277Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Clinical data shape: (2, 63)\n", "Clinical data preview:\n", " !Sample_geo_accession GSM5607752 \\\n", "0 !Sample_characteristics_ch1 sample group: Living donor \n", "1 !Sample_characteristics_ch1 tissue: Glomeruli from kidney biopsy \n", "\n", " GSM5607753 GSM5607754 \\\n", "0 sample group: Living donor sample group: Living donor \n", "1 tissue: Glomeruli from kidney biopsy tissue: Glomeruli from kidney biopsy \n", "\n", " GSM5607755 GSM5607756 \\\n", "0 sample group: Living donor sample group: Living donor \n", "1 tissue: Glomeruli from kidney biopsy tissue: Glomeruli from kidney biopsy \n", "\n", " GSM5607757 GSM5607758 \\\n", "0 sample group: Living donor sample group: Living donor \n", "1 tissue: Glomeruli from kidney biopsy tissue: Glomeruli from kidney biopsy \n", "\n", " GSM5607759 GSM5607760 \\\n", "0 sample group: Living donor sample group: Living donor \n", "1 tissue: Glomeruli from kidney biopsy tissue: Glomeruli from kidney biopsy \n", "\n", " ... GSM5607804 \\\n", "0 ... sample group: FSGS \n", "1 ... tissue: Glomeruli from kidney biopsy \n", "\n", " GSM5607805 GSM5607806 \\\n", "0 sample group: LN-WHO III+V sample group: Interstitial nephritis \n", "1 tissue: Glomeruli from kidney biopsy tissue: Glomeruli from kidney biopsy \n", "\n", " GSM5607807 \\\n", "0 sample group: Hypertensive Nephrosclerosis \n", "1 tissue: Glomeruli from kidney biopsy \n", "\n", " GSM5607808 \\\n", "0 sample group: Unaffected parts of Tumor Nephre... \n", "1 tissue: Glomeruli from kidney biopsy \n", "\n", " GSM5607809 \\\n", "0 sample group: Unaffected parts of Tumor Nephre... \n", "1 tissue: Glomeruli from kidney biopsy \n", "\n", " GSM5607810 \\\n", "0 sample group: Unaffected parts of Tumor Nephre... \n", "1 tissue: Glomeruli from kidney biopsy \n", "\n", " GSM5607811 \\\n", "0 sample group: Unaffected parts of Tumor Nephre... \n", "1 tissue: Glomeruli from kidney biopsy \n", "\n", " GSM5607812 \\\n", "0 sample group: Unaffected parts of Tumor Nephre... \n", "1 tissue: Glomeruli from kidney biopsy \n", "\n", " GSM5607813 \n", "0 sample group: Unaffected parts of Tumor Nephre... \n", "1 tissue: Glomeruli from kidney biopsy \n", "\n", "[2 rows x 63 columns]\n", "\n", "Sample characteristics dictionary:\n", "{0: ['sample group: Living donor', 'sample group: infection-associated GN', 'sample group: FSGS', 'sample group: LN-WHO III', 'sample group: LN-WHO IV', 'sample group: DN', 'sample group: amyloidosis', 'sample group: Membrano-Proliferative GN', 'sample group: MN', 'sample group: AKI', 'sample group: LN-WHO V', 'sample group: FGGS', \"sample group: 2'FSGS\", 'sample group: Thin-BMD', 'sample group: Immuncomplex GN', 'sample group: LN-WHO-V', 'sample group: IgAN', 'sample group: LN-WHO IV+V', 'sample group: LN-WHO III+V', 'sample group: LN-WHO-I/II', 'sample group: chronic Glomerulonephritis (GN) with infiltration by CLL', 'sample group: CKD with mod-severe Interstitial fibrosis', 'sample group: Fibrillary GN', 'sample group: Interstitial nephritis', 'sample group: Hypertensive Nephrosclerosis', 'sample group: Unaffected parts of Tumor Nephrectomy'], 1: ['tissue: Glomeruli from kidney biopsy']}\n", "Loaded gene data shape: (0, 62)\n", "Gene data is empty after mapping.\n", "Cannot proceed with data linking due to missing trait or gene data.\n", "Abnormality detected in the cohort: GSE180393. Preprocessing failed.\n" ] } ], "source": [ "# 1. Let's re-analyze the clinical data to ensure we're accessing the correct rows\n", "background_info, clinical_data = get_background_and_clinical_data(matrix_file)\n", "print(\"Clinical data shape:\", clinical_data.shape)\n", "print(\"Clinical data preview:\")\n", "print(clinical_data.head())\n", "\n", "# Get a better understanding of the sample characteristics\n", "sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n", "print(\"\\nSample characteristics dictionary:\")\n", "print(sample_characteristics_dict)\n", "\n", "# Based on our review of the sample characteristics, let's determine if we have trait data\n", "is_trait_available = False\n", "trait_row = None\n", "age_row = None \n", "gender_row = None\n", "\n", "# Check if sample_characteristics_dict contains data related to chronic kidney disease\n", "for row_idx, values in sample_characteristics_dict.items():\n", " sample_values_str = str(values).lower()\n", " if any(term in sample_values_str for term in ['ckd', 'chronic kidney', 'kidney disease', 'renal']):\n", " trait_row = row_idx\n", " is_trait_available = True\n", " break\n", "\n", "# Normalize gene data if it exists (from previous step)\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", " if gene_data.shape[0] > 0:\n", " # Apply normalization only if gene data has content\n", " gene_data = normalize_gene_symbols_in_index(gene_data)\n", " print(f\"Normalized gene data shape: {gene_data.shape}\")\n", " is_gene_available = True\n", " else:\n", " print(\"Gene data is empty after mapping.\")\n", " is_gene_available = False\n", "except Exception as e:\n", " print(f\"Error loading gene data: {e}\")\n", " is_gene_available = False\n", "\n", "# Save the normalized gene data\n", "if is_gene_available and gene_data.shape[0] > 0:\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", "\n", "# If we have both trait and gene data, proceed with linking\n", "if is_trait_available and is_gene_available and gene_data.shape[0] > 0:\n", " # Define conversion functions for clinical features\n", " def convert_trait(value):\n", " \"\"\"\n", " Convert kidney disease status to binary:\n", " 1 = has chronic kidney disease (any disease state)\n", " 0 = healthy control (living donor)\n", " \"\"\"\n", " if pd.isna(value):\n", " return None\n", " \n", " value = str(value).lower().strip()\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " if 'living donor' in value:\n", " return 0\n", " elif any(term in value for term in ['ckd', 'gn', 'nephritis', 'nephrosclerosis', 'fsgs', 'igan']):\n", " return 1\n", " else:\n", " return None\n", " \n", " # Extract clinical features\n", " try:\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=None,\n", " convert_age=None,\n", " gender_row=None,\n", " convert_gender=None\n", " )\n", " print(f\"Extracted clinical data shape: {selected_clinical_df.shape}\")\n", " print(\"Clinical data preview:\")\n", " print(preview_df(selected_clinical_df))\n", " \n", " # Save 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)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n", " \n", " # Link clinical and genetic data\n", " linked_data = geo_link_clinical_genetic_data(selected_clinical_df, gene_data)\n", " print(f\"Linked data shape: {linked_data.shape}\")\n", " \n", " # Handle missing values\n", " if linked_data.shape[0] > 0:\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\n", " is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n", " \n", " # Validate data quality\n", " note = \"Dataset contains gene expression from kidney biopsies of patients with kidney disease and living donors.\"\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 final 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(\"Data not usable for the trait study - not saving final linked data.\")\n", " else:\n", " print(\"Linked data is empty - cannot proceed with processing.\")\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, # Empty data is essentially biased\n", " df=pd.DataFrame(), # Empty dataframe for metadata\n", " note=\"Failed to link clinical and genetic data - resulting dataset was empty.\"\n", " )\n", " except Exception as e:\n", " print(f\"Error in clinical data processing: {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,\n", " df=pd.DataFrame(),\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, so mark as biased\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 }