{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "9d13be26", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:10:55.341269Z", "iopub.status.busy": "2025-03-25T07:10:55.341089Z", "iopub.status.idle": "2025-03-25T07:10:55.507003Z", "shell.execute_reply": "2025-03-25T07:10:55.506662Z" } }, "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 = \"Intellectual_Disability\"\n", "cohort = \"GSE63870\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Intellectual_Disability\"\n", "in_cohort_dir = \"../../input/GEO/Intellectual_Disability/GSE63870\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Intellectual_Disability/GSE63870.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Intellectual_Disability/gene_data/GSE63870.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Intellectual_Disability/clinical_data/GSE63870.csv\"\n", "json_path = \"../../output/preprocess/Intellectual_Disability/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "46e62773", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "17424f22", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:10:55.508514Z", "iopub.status.busy": "2025-03-25T07:10:55.508368Z", "iopub.status.idle": "2025-03-25T07:10:55.729810Z", "shell.execute_reply": "2025-03-25T07:10:55.729456Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Identification of markers of early dementia in adults with Down syndrome\"\n", "!Series_summary\t\"We aimed at identification of variations of genome expression in white blood cells, which could serve as blood markers of early dementia in adults with Down syndrome\"\n", "!Series_overall_design\t\"Whole genome expression analysis was compared between groups of younger and older patients with or without severe cognitive disability\"\n", "Sample Characteristics Dictionary:\n", "{0: ['age: Young', 'age: Old'], 1: ['condition: severe cognitive disability and early dementia', 'condition: without severe cognitive disability', 'condition: severe cognitive disability'], 2: ['cell type: white blood cell']}\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": "710c3093", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "9e4a3c9f", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:10:55.731069Z", "iopub.status.busy": "2025-03-25T07:10:55.730946Z", "iopub.status.idle": "2025-03-25T07:10:55.740381Z", "shell.execute_reply": "2025-03-25T07:10:55.740077Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Preview of extracted clinical features:\n", "{'GSM1': [1.0, 0.0], 'GSM2': [1.0, 1.0], 'GSM3': [1.0, nan]}\n", "Saved clinical data to ../../output/preprocess/Intellectual_Disability/clinical_data/GSE63870.csv\n" ] } ], "source": [ "import pandas as pd\n", "import os\n", "import json\n", "from typing import Optional, Callable, Dict, Any\n", "\n", "# 1. Gene Expression Data Availability\n", "# Based on the series title and summary, this dataset appears to contain genome expression data in white blood cells\n", "# This is likely gene expression data, not just miRNA or methylation\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "# The trait we're studying is Intellectual_Disability\n", "# From sample characteristics, we can see that row 1 contains information about cognitive disability\n", "trait_row = 1\n", "\n", "# Age information is in row 0\n", "age_row = 0\n", "\n", "# No gender information is available in the sample characteristics\n", "gender_row = None\n", "\n", "# 2.2 Data Type Conversion Functions\n", "def convert_trait(value):\n", " \"\"\"Convert cognitive disability status to binary trait value for Intellectual_Disability.\"\"\"\n", " if value is None or pd.isna(value):\n", " return None\n", " \n", " # Ensure value is treated as string\n", " value = str(value)\n", " \n", " # Extract the value after the colon if exists\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " # Map values to binary 0/1 for Intellectual_Disability\n", " if \"severe cognitive disability\" in value.lower() or \"early dementia\" in value.lower():\n", " return 1\n", " elif \"without severe cognitive disability\" in value.lower():\n", " return 0\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age information to binary categories.\"\"\"\n", " if value is None or pd.isna(value):\n", " return None\n", " \n", " # Ensure value is treated as string\n", " value = str(value)\n", " \n", " # Extract the value after the colon if exists\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " # Convert to binary categories based on provided values\n", " if value.lower() == \"young\":\n", " return 0\n", " elif value.lower() == \"old\":\n", " return 1\n", " else:\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender information to binary.\"\"\"\n", " # Not used in this dataset as gender information is not available\n", " return None\n", "\n", "# 3. Save Metadata - Initial Filtering\n", "# Determine if trait data is available\n", "is_trait_available = trait_row is not None\n", "\n", "# Validate and save cohort information for initial filtering\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 not None, we proceed with clinical feature extraction\n", "if trait_row is not None:\n", " # Make sure the output directory exists\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " \n", " # Get the sample characteristics dictionary\n", " characteristics_dict = {\n", " 0: ['age: Young', 'age: Old'], \n", " 1: ['condition: severe cognitive disability and early dementia', 'condition: without severe cognitive disability', 'condition: severe cognitive disability'], \n", " 2: ['cell type: white blood cell']\n", " }\n", " \n", " # Create sample IDs based on the maximum length of characteristics\n", " max_samples = max(len(values) for values in characteristics_dict.values())\n", " sample_ids = [f\"GSM{i+1}\" for i in range(max_samples)]\n", " \n", " # Create a properly structured DataFrame for geo_select_clinical_features\n", " # Here, rows are characteristics and columns are samples\n", " data = {}\n", " for row_idx, values in characteristics_dict.items():\n", " row_data = {}\n", " for i, sample_id in enumerate(sample_ids):\n", " if i < len(values):\n", " row_data[sample_id] = values[i]\n", " else:\n", " row_data[sample_id] = None\n", " data[row_idx] = row_data\n", " \n", " clinical_data = pd.DataFrame(data).T\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 extracted clinical features\n", " preview_data = preview_df(selected_clinical_df)\n", " print(\"Preview of extracted clinical features:\")\n", " print(preview_data)\n", " \n", " # Save the extracted clinical features to CSV\n", " selected_clinical_df.to_csv(out_clinical_data_file)\n", " print(f\"Saved clinical data to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "7bbdd646", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "fc151e54", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:10:55.741499Z", "iopub.status.busy": "2025-03-25T07:10:55.741387Z", "iopub.status.idle": "2025-03-25T07:10:56.032898Z", "shell.execute_reply": "2025-03-25T07:10:56.032536Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Extracting gene data from matrix file:\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Successfully extracted gene data with 50739 rows\n", "First 20 gene IDs:\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", "\n", "Gene expression data available: True\n" ] } ], "source": [ "# 1. Get the file paths for the SOFT file and matrix file\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# 2. Extract gene expression data from the matrix file\n", "try:\n", " print(\"Extracting gene data from matrix file:\")\n", " gene_data = get_genetic_data(matrix_file)\n", " if gene_data.empty:\n", " print(\"Extracted gene expression data is empty\")\n", " is_gene_available = False\n", " else:\n", " print(f\"Successfully extracted gene data with {len(gene_data.index)} rows\")\n", " print(\"First 20 gene IDs:\")\n", " print(gene_data.index[:20])\n", " is_gene_available = True\n", "except Exception as e:\n", " print(f\"Error extracting gene data: {e}\")\n", " print(\"This dataset appears to have an empty or malformed gene expression matrix\")\n", " is_gene_available = False\n", "\n", "print(f\"\\nGene expression data available: {is_gene_available}\")\n" ] }, { "cell_type": "markdown", "id": "3c8143ee", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "f4ed854d", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:10:56.034186Z", "iopub.status.busy": "2025-03-25T07:10:56.034066Z", "iopub.status.idle": "2025-03-25T07:10:56.035992Z", "shell.execute_reply": "2025-03-25T07:10:56.035715Z" } }, "outputs": [], "source": [ "# Analyzing the gene identifiers in the gene expression data\n", "# Looking at the first 20 gene IDs, I can see:\n", "# 1. Control probes like \"(+)E1A_r60_1\", \"(+)E1A_r60_3\", etc.\n", "# 2. Array/probe IDs like \"A_19_P00315452\", \"A_19_P00315459\", etc.\n", "# 3. Other identifiers like \"3xSLv1\"\n", "\n", "# These are not standard human gene symbols (like BRCA1, TP53, etc.)\n", "# They appear to be array-specific probe IDs from a microarray platform\n", "# These need to be mapped to standard gene symbols\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "625f913e", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "300d9880", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:10:56.037146Z", "iopub.status.busy": "2025-03-25T07:10:56.037031Z", "iopub.status.idle": "2025-03-25T07:11:00.587709Z", "shell.execute_reply": "2025-03-25T07:11:00.587349Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Extracting gene annotation data from SOFT file...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Successfully extracted gene annotation data with 2486259 rows\n", "\n", "Gene annotation preview (first few rows):\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", "Column names in gene annotation data:\n", "['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", "\n", "The dataset contains GenBank accessions (GB_ACC) that could be used for gene mapping.\n", "Number of rows with GenBank accessions: 38153 out of 2486259\n", "\n", "The dataset contains genomic regions (SPOT_ID) that could be used for location-based gene mapping.\n", "Example SPOT_ID format: CONTROL\n" ] } ], "source": [ "# 1. Extract gene annotation data from the SOFT file\n", "print(\"Extracting gene annotation data from SOFT file...\")\n", "try:\n", " # Use the library function to extract gene annotation\n", " gene_annotation = get_gene_annotation(soft_file)\n", " print(f\"Successfully extracted gene annotation data with {len(gene_annotation.index)} rows\")\n", " \n", " # Preview the annotation DataFrame\n", " print(\"\\nGene annotation preview (first few rows):\")\n", " print(preview_df(gene_annotation))\n", " \n", " # Show column names to help identify which columns we need for mapping\n", " print(\"\\nColumn names in gene annotation data:\")\n", " print(gene_annotation.columns.tolist())\n", " \n", " # Check for relevant mapping columns\n", " if 'GB_ACC' in gene_annotation.columns:\n", " print(\"\\nThe dataset contains GenBank accessions (GB_ACC) that could be used for gene mapping.\")\n", " # Count non-null values in GB_ACC column\n", " non_null_count = gene_annotation['GB_ACC'].count()\n", " print(f\"Number of rows with GenBank accessions: {non_null_count} out of {len(gene_annotation)}\")\n", " \n", " if 'SPOT_ID' in gene_annotation.columns:\n", " print(\"\\nThe dataset contains genomic regions (SPOT_ID) that could be used for location-based gene mapping.\")\n", " print(\"Example SPOT_ID format:\", gene_annotation['SPOT_ID'].iloc[0])\n", " \n", "except Exception as e:\n", " print(f\"Error processing gene annotation data: {e}\")\n", " is_gene_available = False\n" ] }, { "cell_type": "markdown", "id": "63959a1d", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "5c98a4f1", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:11:00.589079Z", "iopub.status.busy": "2025-03-25T07:11:00.588937Z", "iopub.status.idle": "2025-03-25T07:11:01.424419Z", "shell.execute_reply": "2025-03-25T07:11:01.424018Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Using ID as probe identifier and GENE_SYMBOL as gene symbol\n", "Creating gene mapping dataframe...\n", "Created gene mapping with 46204 entries\n", "Preview of gene mapping:\n", "{'ID': ['A_23_P117082', 'A_33_P3246448', 'A_33_P3318220', 'A_33_P3236322', 'A_33_P3319925'], 'Gene': ['HEBP1', 'KCNE4', 'BPIFA3', 'LOC100129869', 'IRG1']}\n", "Converting probe-level measurements to gene expression data...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Created gene expression data with 20353 genes\n", "Preview of gene expression data:\n", " GSM1558696 GSM1558697 GSM1558698 GSM1558699 GSM1558700 \\\n", "Gene \n", "A1BG -1.882027 -1.537594 -1.531755 -0.498507 0.175755 \n", "A1BG-AS1 -0.319541 -0.085776 -0.640145 -0.149423 0.366026 \n", "A1CF -0.600164 -0.309273 -0.249359 0.435776 0.290430 \n", "\n", " GSM1558701 GSM1558702 GSM1558703 GSM1558704 GSM1558705 ... \\\n", "Gene ... \n", "A1BG 1.084357 0.145071 0.832431 1.468052 2.828776 ... \n", "A1BG-AS1 1.032678 0.328191 -0.327742 -0.106659 0.174874 ... \n", "A1CF 0.664791 0.622737 -0.218599 0.195794 0.248855 ... \n", "\n", " GSM1558734 GSM1558735 GSM1558736 GSM1558737 GSM1558738 \\\n", "Gene \n", "A1BG 0.850051 -0.918105 -0.047458 1.490184 -0.551898 \n", "A1BG-AS1 0.711697 0.665669 1.235332 0.210070 -0.119289 \n", "A1CF -0.215270 -0.107210 1.898089 0.880331 0.484042 \n", "\n", " GSM1558739 GSM1558740 GSM1558741 GSM1558742 GSM1558743 \n", "Gene \n", "A1BG -2.392812 -0.228626 -0.528625 0.882180 -1.404017 \n", "A1BG-AS1 0.055974 -0.628787 -0.016772 0.615229 0.504567 \n", "A1CF 0.126495 0.461012 0.424277 0.429027 0.305664 \n", "\n", "[3 rows x 48 columns]\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Saved gene expression data to ../../output/preprocess/Intellectual_Disability/gene_data/GSE63870.csv\n" ] } ], "source": [ "# 1. Determine which columns to use for gene mapping\n", "# Based on the gene expression data and gene annotation preview, we can see:\n", "# - ID column in the annotation contains probe IDs that match the gene expression data index\n", "# - GENE_SYMBOL column contains the human gene symbols we want to map to\n", "\n", "probe_id_col = 'ID'\n", "gene_symbol_col = 'GENE_SYMBOL'\n", "\n", "print(f\"Using {probe_id_col} as probe identifier and {gene_symbol_col} as gene symbol\")\n", "\n", "# 2. Get a gene mapping dataframe by extracting the relevant columns\n", "print(\"Creating gene mapping dataframe...\")\n", "gene_mapping = get_gene_mapping(gene_annotation, prob_col=probe_id_col, gene_col=gene_symbol_col)\n", "print(f\"Created gene mapping with {len(gene_mapping)} entries\")\n", "print(\"Preview of gene mapping:\")\n", "print(preview_df(gene_mapping))\n", "\n", "# 3. Apply gene mapping to convert probe-level measurements to gene expression data\n", "print(\"Converting probe-level measurements to gene expression data...\")\n", "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n", "print(f\"Created gene expression data with {len(gene_data)} genes\")\n", "\n", "# Preview the gene expression data\n", "print(\"Preview of gene expression data:\")\n", "print(gene_data.head(3))\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\"Saved gene expression data to {out_gene_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "573c51ff", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "07ec01f5", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:11:01.425792Z", "iopub.status.busy": "2025-03-25T07:11:01.425664Z", "iopub.status.idle": "2025-03-25T07:11:08.440584Z", "shell.execute_reply": "2025-03-25T07:11:08.440122Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Normalizing gene symbols in the expression data...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data saved to ../../output/preprocess/Intellectual_Disability/gene_data/GSE63870.csv\n", "Normalized gene data shape: (19847, 48)\n", "\n", "Extracting clinical data from source...\n", "\n", "Processing clinical data...\n", "Clinical data shape: (2, 48)\n", "Clinical data index: ['Intellectual_Disability', 'Age']\n", "Clinical data columns: ['GSM1558696', 'GSM1558697', 'GSM1558698', 'GSM1558699', 'GSM1558700', 'GSM1558701', 'GSM1558702', 'GSM1558703', 'GSM1558704', 'GSM1558705', 'GSM1558706', 'GSM1558707', 'GSM1558708', 'GSM1558709', 'GSM1558710', 'GSM1558711', 'GSM1558712', 'GSM1558713', 'GSM1558714', 'GSM1558715', 'GSM1558716', 'GSM1558717', 'GSM1558718', 'GSM1558719', 'GSM1558720', 'GSM1558721', 'GSM1558722', 'GSM1558723', 'GSM1558724', 'GSM1558725', 'GSM1558726', 'GSM1558727', 'GSM1558728', 'GSM1558729', 'GSM1558730', 'GSM1558731', 'GSM1558732', 'GSM1558733', 'GSM1558734', 'GSM1558735', 'GSM1558736', 'GSM1558737', 'GSM1558738', 'GSM1558739', 'GSM1558740', 'GSM1558741', 'GSM1558742', 'GSM1558743']\n", "Gene data has 48 samples\n", "First few gene data sample IDs: ['GSM1558696', 'GSM1558697', 'GSM1558698', 'GSM1558699', 'GSM1558700']\n", "\n", "Linking clinical and genetic data...\n", "Linked data shape: (48, 19849)\n", "\n", "Handling missing values...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "After handling missing values, data shape: (48, 19849)\n", "\n", "Checking for bias in features...\n", "Quartiles for 'Intellectual_Disability':\n", " 25%: 1.0\n", " 50% (Median): 1.0\n", " 75%: 1.0\n", "Min: 1.0\n", "Max: 1.0\n", "The distribution of the feature 'Intellectual_Disability' in this dataset is severely biased.\n", "\n", "Quartiles for 'Age':\n", " 25%: 0.0\n", " 50% (Median): 0.0\n", " 75%: 1.0\n", "Min: 0.0\n", "Max: 1.0\n", "The distribution of the feature 'Age' in this dataset is fine.\n", "\n", "\n", "Performing final validation...\n", "Dataset not usable for Intellectual_Disability association studies. Data not saved.\n" ] } ], "source": [ "# 1. Normalize gene symbols in the gene expression data\n", "print(\"Normalizing gene symbols in the expression data...\")\n", "try:\n", " # If previous steps have already loaded gene_data\n", " normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", " \n", " # Create directory if it doesn't exist\n", " os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", " \n", " # Save normalized gene data\n", " normalized_gene_data.to_csv(out_gene_data_file)\n", " print(f\"Normalized gene data saved to {out_gene_data_file}\")\n", " print(f\"Normalized gene data shape: {normalized_gene_data.shape}\")\n", "except Exception as e:\n", " print(f\"Error normalizing gene data: {e}\")\n", " is_gene_available = False\n", "\n", "# 2. Load the original clinical data and recreate it properly\n", "print(\"\\nExtracting clinical data from source...\")\n", "try:\n", " # Re-extract background information and sample characteristics from matrix file\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", " # Process the clinical data to extract trait and age information\n", " print(\"\\nProcessing clinical data...\")\n", " # Extract the sample IDs which should match the gene expression data\n", " sample_ids = clinical_data['!Sample_geo_accession'].tolist()\n", " \n", " # Get feature data from specified rows\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", " # Display information about clinical data\n", " print(f\"Clinical data shape: {selected_clinical_df.shape}\")\n", " print(f\"Clinical data index: {selected_clinical_df.index.tolist()}\")\n", " print(f\"Clinical data columns: {selected_clinical_df.columns.tolist()}\")\n", " \n", " # Get gene data sample IDs\n", " gene_sample_ids = normalized_gene_data.columns.tolist()\n", " print(f\"Gene data has {len(gene_sample_ids)} samples\")\n", " print(f\"First few gene data sample IDs: {gene_sample_ids[:5]}\")\n", " \n", " # Link clinical and genetic data using the geo helper function\n", " print(\"\\nLinking clinical and genetic data...\")\n", " linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)\n", " print(f\"Linked data shape: {linked_data.shape}\")\n", " \n", " # Check if the linked data has enough samples\n", " if linked_data.shape[0] < 3:\n", " raise ValueError(\"Not enough samples after linking clinical and genetic data\")\n", " \n", " # 3. Handle missing values systematically\n", " print(\"\\nHandling missing values...\")\n", " linked_data = handle_missing_values(linked_data, trait)\n", " print(f\"After handling missing values, data shape: {linked_data.shape}\")\n", " \n", " # 4. Determine whether features are biased\n", " print(\"\\nChecking for bias in features...\")\n", " is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n", " \n", " # 5. Final validation and save metadata\n", " print(\"\\nPerforming final validation...\")\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=\"Down syndrome study: severe cognitive disability vs without severe cognitive disability.\"\n", " )\n", " \n", " # 6. Save the linked data if usable\n", " if is_usable:\n", " # Create directory if it doesn't exist\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " \n", " # Save linked data\n", " linked_data.to_csv(out_data_file)\n", " print(f\"Linked data saved to {out_data_file}\")\n", " else:\n", " print(f\"Dataset not usable for {trait} association studies. Data not saved.\")\n", "\n", "except Exception as e:\n", " print(f\"Error in data linking or processing: {e}\")\n", " print(\"Detailed error information:\")\n", " import traceback\n", " traceback.print_exc()\n", " \n", " # Create a minimal dataframe for validation purposes\n", " linked_data = pd.DataFrame({trait: [0, 1]})\n", " \n", " # Perform final validation with appropriate flags\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=True, # Not relevant since data isn't usable\n", " df=linked_data,\n", " note=\"Failed to link gene and clinical data: \" + str(e)\n", " )\n", " print(f\"Dataset usability: {is_usable}\")" ] } ], "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 }