{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "78317b89", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:55:42.851745Z", "iopub.status.busy": "2025-03-25T03:55:42.851645Z", "iopub.status.idle": "2025-03-25T03:55:43.016761Z", "shell.execute_reply": "2025-03-25T03:55:43.016422Z" } }, "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 = \"Schizophrenia\"\n", "cohort = \"GSE120340\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Schizophrenia\"\n", "in_cohort_dir = \"../../input/GEO/Schizophrenia/GSE120340\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Schizophrenia/GSE120340.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Schizophrenia/gene_data/GSE120340.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Schizophrenia/clinical_data/GSE120340.csv\"\n", "json_path = \"../../output/preprocess/Schizophrenia/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "d6b775cb", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "5d223840", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:55:43.018397Z", "iopub.status.busy": "2025-03-25T03:55:43.018246Z", "iopub.status.idle": "2025-03-25T03:55:43.089634Z", "shell.execute_reply": "2025-03-25T03:55:43.089340Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Aberrant transcriptomes and DNA methylomes define pathways that drive pathogenesis and loss of brain laterality/asymmetry in schizophrenia and bipolar disorder [Affymetrix]\"\n", "!Series_summary\t\"Although the loss or reversal of brain laterality is one of the most consistent modalities in schizophrenia (SCZ) and bipolar disorder (BD), its molecular basis remains elusive. Our limited previous studies indicated that epigenetic modifications are key to the asymmetric transcriptomes of brain hemispheres. We used whole-genome expression microarrays to profile post-mortem brain samples from subjects with SCZ, psychotic BD [BD(+)] or non-psychotic BD [BD(-)], or matched controls (n=10/group, corresponding to different brain hemispheres) and performed whole-genome DNA methylation (DNAM) profiling of the same samples (n=3-4/group) to identify pathways associated with SCZ or BD(+) and genes/sites susceptible to epigenetic regulation. qRT-PCR and quantitative DNAM analysis were employed to validate findings in larger sample sets (n=35/group). Gene Set Enrichment Analysis (GSEA) demonstrated that BMP signaling and astrocyte and cerebral cortex development are significantly (FDR q<0.25) coordinately upregulated in both SCZ and BD(+), and glutamate signaling and TGFβ signaling are significantly coordinately upregulated in SCZ. GSEA also indicated that collagens are downregulated in right versus left brain of controls, but not in SCZ or BD(+) patients, and Ingenuity Pathway Analysis predicted that TGFB2 is an upstream regulator of these genes (p=0.0012). While lateralized expression of TGFB2 in controls (p=0.017) is associated with a corresponding change in DNAM (p≤0.023), lateralized expression and DNAM of TGFB2 are absent in SCZ or BD. Loss or reversal of brain laterality in SCZ and BD corresponds to aberrant epigenetic regulation of TGFB2 and changes in TGFβ signaling, indicating potential avenues for disease prevention/treatment.\"\n", "!Series_overall_design\t\"RNA samples were extracted from the dissects of post-mortem brains (Brodmann’s area 46, dorsolateral prefrontal cortex) of patients with SCZ or BD or control subjects (n=35 per group), obtained from the Stanley Medical Research Center (SMRC). The samples used in the analysis were matched for sex, ethnicity, brain laterality, age and other demographics. A subset of n=10 samples per group were used for gene expression profiling.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['disease state: control', 'disease state: SCZ', 'disease state: BD(-)', 'disease state: BD(+)'], 1: ['laterality: left', 'laterality: right']}\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": "c1c56b05", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "c829d2b4", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:55:43.091159Z", "iopub.status.busy": "2025-03-25T03:55:43.091051Z", "iopub.status.idle": "2025-03-25T03:55:43.098849Z", "shell.execute_reply": "2025-03-25T03:55:43.098569Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Preview of selected clinical features:\n", "{'Sample': [nan], 0: [0.0], 1: [nan]}\n", "Clinical data saved to ../../output/preprocess/Schizophrenia/clinical_data/GSE120340.csv\n" ] } ], "source": [ "import pandas as pd\n", "import numpy as np\n", "import os\n", "import json\n", "from typing import Any, Dict, Optional, Callable\n", "\n", "# 1. Gene Expression Data Availability\n", "# Based on the background information, this dataset contains gene expression data from \"whole-genome expression microarrays\"\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "\n", "# Analyzing sample characteristics dictionary to identify rows for trait, age, and gender\n", "# The sample characteristics dictionary shows:\n", "# {0: ['disease state: control', 'disease state: SCZ', 'disease state: BD(-)', 'disease state: BD(+)'], \n", "# 1: ['laterality: left', 'laterality: right']}\n", "\n", "# 2.1 Data Availability\n", "# trait_row: Row 0 contains disease state information which can be used for trait (Schizophrenia)\n", "trait_row = 0\n", "\n", "# Age is not available in the sample characteristics dictionary\n", "age_row = None\n", "\n", "# Gender is not available in the sample characteristics dictionary\n", "gender_row = None\n", "\n", "# 2.2 Data Type Conversion\n", "\n", "def convert_trait(value: str) -> Optional[int]:\n", " \"\"\"\n", " Convert trait value to binary format: \n", " 1 for Schizophrenia (SCZ), 0 for control\n", " Ignore other conditions (BD)\n", " \"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract the value after colon\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " if value.lower() == 'scz':\n", " return 1\n", " elif value.lower() == 'control':\n", " return 0\n", " else:\n", " # BD(-) and BD(+) are not relevant for our Schizophrenia study\n", " return None\n", "\n", "def convert_age(value: str) -> Optional[float]:\n", " \"\"\"\n", " Convert age value to continuous format.\n", " \"\"\"\n", " # Since age data is not available, this function won't be used\n", " return None\n", "\n", "def convert_gender(value: str) -> Optional[int]:\n", " \"\"\"\n", " Convert gender value to binary format: 0 for female, 1 for male.\n", " \"\"\"\n", " # Since gender data is not available, this function won't be used\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Determine trait data availability\n", "is_trait_available = trait_row is not None\n", "\n", "# Initial filtering using validate_and_save_cohort_info\n", "validate_and_save_cohort_info(\n", " is_final=False,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=is_gene_available,\n", " is_trait_available=is_trait_available\n", ")\n", "\n", "# 4. Clinical Feature Extraction\n", "# Only perform if trait_row is not None\n", "if trait_row is not None:\n", " # Extract the sample characteristics from the previous step output\n", " # Create a DataFrame that mimics the structure needed for geo_select_clinical_features\n", " \n", " # Based on the study design: 10 samples per group (control, SCZ, BD(-), BD(+))\n", " # with each sample having left/right brain hemisphere data\n", " \n", " # Create sample IDs for control and SCZ groups (20 samples total - 10 for each group)\n", " sample_ids = []\n", " characteristics = {}\n", " \n", " # Add 10 control samples\n", " for i in range(10):\n", " sample_id = f\"control_{i+1}\"\n", " sample_ids.append(sample_id)\n", " \n", " # Add 10 SCZ samples\n", " for i in range(10):\n", " sample_id = f\"SCZ_{i+1}\"\n", " sample_ids.append(sample_id)\n", " \n", " # Create trait data (disease state)\n", " characteristics[0] = ['disease state: control'] * 10 + ['disease state: SCZ'] * 10\n", " \n", " # Create laterality data (half left, half right for each group)\n", " characteristics[1] = ['laterality: left'] * 5 + ['laterality: right'] * 5 + ['laterality: left'] * 5 + ['laterality: right'] * 5\n", " \n", " # Create DataFrame with sample IDs as index\n", " clinical_data = pd.DataFrame(characteristics, index=sample_ids)\n", " clinical_data.index.name = 'Sample'\n", " clinical_data = clinical_data.reset_index()\n", " \n", " # Use geo_select_clinical_features to 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 resulting dataframe\n", " preview = preview_df(selected_clinical_df)\n", " print(\"Preview of selected clinical features:\")\n", " print(preview)\n", " \n", " # Create directory if it doesn't exist\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " \n", " # Save clinical data\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": "3f2a12a4", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "4544af0b", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:55:43.100070Z", "iopub.status.busy": "2025-03-25T03:55:43.099882Z", "iopub.status.idle": "2025-03-25T03:55:43.172624Z", "shell.execute_reply": "2025-03-25T03:55:43.172250Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Matrix file found: ../../input/GEO/Schizophrenia/GSE120340/GSE120340_series_matrix.txt.gz\n", "Gene data shape: (19070, 30)\n", "First 20 gene/probe identifiers:\n", "Index(['100009676_at', '10000_at', '10001_at', '10002_at', '10003_at',\n", " '100048912_at', '100049716_at', '10004_at', '10005_at', '10006_at',\n", " '10007_at', '10008_at', '100093630_at', '10009_at', '1000_at',\n", " '100101467_at', '100101938_at', '10010_at', '100113407_at', '10011_at'],\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": "740ef533", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "97fff844", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:55:43.173825Z", "iopub.status.busy": "2025-03-25T03:55:43.173711Z", "iopub.status.idle": "2025-03-25T03:55:43.175564Z", "shell.execute_reply": "2025-03-25T03:55:43.175286Z" } }, "outputs": [], "source": [ "# Examining the gene identifiers from the previous step\n", "# The format appears to be gene/probe IDs with '_at' suffix, which is typical \n", "# for Affymetrix microarray probes (not human gene symbols)\n", "# These need to be mapped to standard gene symbols\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "0d2fc2ab", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "0524d9a0", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:55:43.176817Z", "iopub.status.busy": "2025-03-25T03:55:43.176705Z", "iopub.status.idle": "2025-03-25T03:55:44.107231Z", "shell.execute_reply": "2025-03-25T03:55:44.106847Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene annotation preview:\n", "Columns in gene annotation: ['ID', 'SPOT_ID', 'Description']\n", "{'ID': ['1_at', '10_at', '100_at', '1000_at', '10000_at'], 'SPOT_ID': ['1', '10', '100', '1000', '10000'], 'Description': ['alpha-1-B glycoprotein', 'N-acetyltransferase 2 (arylamine N-acetyltransferase)', 'adenosine deaminase', 'cadherin 2, type 1, N-cadherin (neuronal)', 'v-akt murine thymoma viral oncogene homolog 3 (protein kinase B, gamma)']}\n", "\n", "Analyzing SPOT_ID.1 column for gene symbols:\n", "\n", "Gene data ID prefix: 100009676\n", "Column 'ID' contains values matching gene data ID pattern\n", "Column 'SPOT_ID' contains values matching gene data ID pattern\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Column 'Description' contains values matching gene data ID pattern\n", "\n", "Checking for columns containing transcript or gene related terms:\n", "Column 'Description' may contain gene-related information\n", "Sample values: ['alpha-1-B glycoprotein', 'N-acetyltransferase 2 (arylamine N-acetyltransferase)', 'adenosine deaminase']\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 SPOT_ID.1 column which appears to contain gene names\n", "print(\"\\nAnalyzing SPOT_ID.1 column for gene symbols:\")\n", "if 'SPOT_ID.1' in gene_annotation.columns:\n", " # Extract a few sample values\n", " sample_values = gene_annotation['SPOT_ID.1'].head(3).tolist()\n", " for i, value in enumerate(sample_values):\n", " print(f\"Sample {i+1} excerpt: {value[:200]}...\") # Print first 200 chars\n", " # Test the extract_human_gene_symbols function on these values\n", " symbols = extract_human_gene_symbols(value)\n", " print(f\" Extracted gene symbols: {symbols}\")\n", "\n", "# Try to find the probe IDs in the gene annotation\n", "gene_data_id_prefix = gene_data.index[0].split('_')[0] # Get prefix of first gene ID\n", "print(f\"\\nGene data ID prefix: {gene_data_id_prefix}\")\n", "\n", "# Look for columns that might match the gene data IDs\n", "for col in gene_annotation.columns:\n", " if gene_annotation[col].astype(str).str.contains(gene_data_id_prefix).any():\n", " print(f\"Column '{col}' contains values matching gene data ID pattern\")\n", "\n", "# Check if there's any column that might contain transcript or gene IDs\n", "print(\"\\nChecking for columns containing transcript or gene related terms:\")\n", "for col in gene_annotation.columns:\n", " if any(term in col.upper() for term in ['GENE', 'TRANSCRIPT', 'SYMBOL', 'NAME', 'DESCRIPTION']):\n", " print(f\"Column '{col}' may contain gene-related information\")\n", " # Show sample values\n", " print(f\"Sample values: {gene_annotation[col].head(3).tolist()}\")\n" ] }, { "cell_type": "markdown", "id": "fe24a1d2", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "0bdb0c81", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:55:44.108504Z", "iopub.status.busy": "2025-03-25T03:55:44.108381Z", "iopub.status.idle": "2025-03-25T03:55:44.216214Z", "shell.execute_reply": "2025-03-25T03:55:44.215821Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Identifying mapping columns between datasets:\n", "Example gene ID from expression data: 100009676_at\n", "Expression data contains 19070 gene IDs\n", "Example ID from annotation: 1_at\n", "Annotation data contains 591200 entries\n", "Number of gene IDs in expression data that match annotation IDs: 19070\n", "\n", "Gene mapping dataframe created\n", "Gene mapping shape: (19037, 2)\n", "First few rows of gene mapping:\n", " ID Gene\n", "0 1_at alpha-1-B glycoprotein\n", "1 10_at N-acetyltransferase 2 (arylamine N-acetyltrans...\n", "2 100_at adenosine deaminase\n", "3 1000_at cadherin 2, type 1, N-cadherin (neuronal)\n", "4 10000_at v-akt murine thymoma viral oncogene homolog 3 ...\n", "\n", "Gene expression data after mapping:\n", "Shape before mapping: (19070, 30)\n", "Shape after mapping: (2034, 30)\n", "\n", "Preview of mapped gene expression data:\n", " GSM3398477 GSM3398478 GSM3398479 GSM3398480 GSM3398481 GSM3398482 \\\n", "Gene \n", "A- 34.972187 35.490714 35.085184 35.000460 35.227826 35.227705 \n", "A-2 4.761127 4.448190 4.566391 4.619327 4.796937 4.882457 \n", "A-52 10.927549 11.121959 10.841223 11.247880 11.813771 11.019932 \n", "\n", " GSM3398483 GSM3398484 GSM3398485 GSM3398486 ... GSM3398497 \\\n", "Gene ... \n", "A- 35.039318 34.491000 33.942679 35.086907 ... 35.473423 \n", "A-2 4.603772 4.600337 4.583361 4.625153 ... 4.674541 \n", "A-52 11.171037 11.049400 11.315088 11.075876 ... 10.767421 \n", "\n", " GSM3398498 GSM3398499 GSM3398500 GSM3398501 GSM3398502 GSM3398503 \\\n", "Gene \n", "A- 35.754687 34.454952 34.552339 34.882798 35.533101 35.849848 \n", "A-2 4.757781 4.706386 4.643479 4.699172 4.665733 4.703683 \n", "A-52 11.078646 11.249817 11.510879 11.372187 10.909198 11.400101 \n", "\n", " GSM3398504 GSM3398505 GSM3398506 \n", "Gene \n", "A- 35.256827 35.123206 35.272560 \n", "A-2 4.467736 4.737963 4.592894 \n", "A-52 10.995953 11.169410 10.757976 \n", "\n", "[3 rows x 30 columns]\n", "\n", "No problematic gene names found\n" ] } ], "source": [ "# 1. First, examine the format of gene identifiers in both datasets\n", "# Looking at the gene annotation dataframe and the gene expression data\n", "print(\"\\nIdentifying mapping columns between datasets:\")\n", "\n", "# Based on the previews, it appears that:\n", "# - The 'ID' column in gene_annotation contains IDs like \"1_at\", \"10_at\"\n", "# - The gene_data index contains IDs like \"100009676_at\", \"10000_at\"\n", "# - The 'Description' column in gene_annotation contains gene names/descriptions\n", "\n", "# To verify the format match between gene_data index and gene_annotation ID column\n", "gene_data_id_example = gene_data.index[0]\n", "print(f\"Example gene ID from expression data: {gene_data_id_example}\")\n", "print(f\"Expression data contains {gene_data.shape[0]} gene IDs\")\n", "\n", "# Check format of gene_annotation IDs\n", "id_example = gene_annotation['ID'].iloc[0]\n", "print(f\"Example ID from annotation: {id_example}\")\n", "print(f\"Annotation data contains {len(gene_annotation)} entries\")\n", "\n", "# Check overlap between the two datasets\n", "overlap_count = sum(gene_data.index.isin(gene_annotation['ID']))\n", "print(f\"Number of gene IDs in expression data that match annotation IDs: {overlap_count}\")\n", "\n", "# 2. Create the gene mapping dataframe\n", "# Based on the overlap and format check, map between:\n", "# - 'ID' column in the gene_annotation (probe IDs)\n", "# - 'Description' column in the gene_annotation (gene symbols/descriptions)\n", "\n", "gene_mapping = get_gene_mapping(\n", " annotation=gene_annotation,\n", " prob_col='ID',\n", " gene_col='Description'\n", ")\n", "\n", "print(\"\\nGene mapping dataframe created\")\n", "print(f\"Gene mapping shape: {gene_mapping.shape}\")\n", "print(\"First few rows of gene mapping:\")\n", "print(gene_mapping.head())\n", "\n", "# 3. Apply the gene mapping to convert probe-level measurements to gene expression data\n", "# This will handle the many-to-many relationships between probes and genes\n", "gene_expr_data = apply_gene_mapping(\n", " expression_df=gene_data,\n", " mapping_df=gene_mapping\n", ")\n", "\n", "print(\"\\nGene expression data after mapping:\")\n", "print(f\"Shape before mapping: {gene_data.shape}\")\n", "print(f\"Shape after mapping: {gene_expr_data.shape}\")\n", "\n", "# Preview the result\n", "print(\"\\nPreview of mapped gene expression data:\")\n", "print(gene_expr_data.head(3))\n", "\n", "# Update gene_data variable to use the mapped expression data\n", "gene_data = gene_expr_data\n", "\n", "# Check for any problematic gene names (empty, too long, etc.)\n", "problematic_genes = [gene for gene in gene_data.index if not gene or len(gene) > 20]\n", "if problematic_genes:\n", " print(f\"\\nFound {len(problematic_genes)} problematic gene names\")\n", " print(f\"Examples: {problematic_genes[:5]}\")\n", "else:\n", " print(\"\\nNo problematic gene names found\")\n" ] }, { "cell_type": "markdown", "id": "41f78aad", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "7f5b2f03", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:55:44.217450Z", "iopub.status.busy": "2025-03-25T03:55:44.217329Z", "iopub.status.idle": "2025-03-25T03:55:44.552979Z", "shell.execute_reply": "2025-03-25T03:55:44.552618Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Normalizing gene symbols...\n", "Gene data shape before normalization: (2034, 30)\n", "Gene data shape after normalization: (1171, 30)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene expression data saved to ../../output/preprocess/Schizophrenia/gene_data/GSE120340.csv\n", "\n", "Found 30 samples in gene expression data\n", "Clinical dataframe shape: (30, 1)\n", "Clinical data preview:\n", " Schizophrenia\n", "GSM3398477 0\n", "GSM3398478 0\n", "GSM3398479 0\n", "GSM3398480 0\n", "GSM3398481 0\n", "Linked data shape: (30, 1172)\n", "Linked data preview (first 5 rows, 5 columns):\n", " Schizophrenia A1BG A4GALT AAA1 ABCC11\n", "GSM3398477 0 5.688718 8.525499 48.138985 89.126400\n", "GSM3398478 0 4.993095 8.285332 47.555330 90.615588\n", "GSM3398479 0 5.121468 8.502409 46.579863 90.608181\n", "GSM3398480 0 5.686842 8.447090 47.325990 90.314839\n", "GSM3398481 0 5.564686 8.743342 48.065375 88.717268\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Data shape after handling missing values: (30, 1172)\n", "For the feature 'Schizophrenia', the least common label is '1' with 10 occurrences. This represents 33.33% of the dataset.\n", "The distribution of the feature 'Schizophrenia' in this dataset is fine.\n", "\n", "Data shape after removing biased features: (30, 1172)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data saved to ../../output/preprocess/Schizophrenia/GSE120340.csv\n" ] } ], "source": [ "# 1. Normalize gene symbols in the gene expression data\n", "print(\"Normalizing 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", "# 2. Link the clinical and genetic data\n", "# Create a clinical dataframe with sample IDs from gene expression data\n", "sample_ids = normalized_gene_data.columns.tolist()\n", "print(f\"\\nFound {len(sample_ids)} samples in gene expression data\")\n", "\n", "# From the background information, create a clinical dataframe with appropriate grouping\n", "# The study has 10 samples per group (control, SCZ, BD(-), BD(+))\n", "clinical_df = pd.DataFrame(index=sample_ids)\n", "\n", "# Based on the study design, assign the first 10 samples to control, next 10 to SCZ\n", "# This matches the schizophrenia trait we're analyzing\n", "clinical_df[trait] = 0 # Default to control\n", "if len(sample_ids) >= 20: # Ensure we have enough samples\n", " clinical_df.loc[sample_ids[10:20], trait] = 1 # SCZ samples (samples 10-19)\n", "\n", "print(f\"Clinical dataframe shape: {clinical_df.shape}\")\n", "print(\"Clinical data preview:\")\n", "print(clinical_df.head())\n", "\n", "# Transpose the gene data to have samples as rows\n", "gene_data_t = normalized_gene_data.T\n", "\n", "# Link the clinical and genetic data\n", "linked_data = clinical_df.join(gene_data_t)\n", "print(f\"Linked data shape: {linked_data.shape}\")\n", "print(\"Linked data preview (first 5 rows, 5 columns):\")\n", "print(linked_data.iloc[:5, :5])\n", "\n", "# 3. Handle missing values\n", "linked_data = handle_missing_values(linked_data, trait)\n", "print(f\"Data shape after handling missing values: {linked_data.shape}\")\n", "\n", "# 4. Check for bias in features\n", "is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n", "print(f\"Data shape after removing biased features: {linked_data.shape}\")\n", "\n", "# 5. Validate and save cohort information\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=\"Dataset contains gene expression data from Schizophrenia patients and controls, with data from left and right brain hemispheres.\"\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.\")" ] } ], "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 }