{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "4b0c5d2c", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:07:46.479228Z", "iopub.status.busy": "2025-03-25T07:07:46.479048Z", "iopub.status.idle": "2025-03-25T07:07:46.640466Z", "shell.execute_reply": "2025-03-25T07:07:46.640128Z" } }, "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 = \"Cardiovascular_Disease\"\n", "cohort = \"GSE285666\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Cardiovascular_Disease\"\n", "in_cohort_dir = \"../../input/GEO/Cardiovascular_Disease/GSE285666\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Cardiovascular_Disease/GSE285666.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Cardiovascular_Disease/gene_data/GSE285666.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Cardiovascular_Disease/clinical_data/GSE285666.csv\"\n", "json_path = \"../../output/preprocess/Cardiovascular_Disease/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "89f49db4", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "f5b8acc8", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:07:46.641835Z", "iopub.status.busy": "2025-03-25T07:07:46.641699Z", "iopub.status.idle": "2025-03-25T07:07:46.723729Z", "shell.execute_reply": "2025-03-25T07:07:46.723438Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Exon- and gene-Level transcriptional profiling in Lymphoblastoid Cell Lines (LCLs) from Williams syndrome patients and controls\"\n", "!Series_summary\t\"Williams syndrome (WS), characterized by positive sociality, provides a unique model for studying transcriptional networks underlying social dysfunction, relevant to disorders like autism spectrum disorder (ASD) and schizophrenia (SCHZ). In a cohort lymphoblastoid cell lines derived from 52 individuals (34 WS patients, 18 parental controls), genome-wide exon-level arrays identified a core set of differentially expressed genes (DEGs), with WS-deleted genes ranking among the top transcripts. Findings were validated by PCR, RNA-seq, and western blots.\"\n", "!Series_summary\t\"Network analyses revealed perturbed actin cytoskeletal signaling in excitatory dendritic spines, alongside interactions in MAPK, IGF1-PI3K-AKT-mTOR/insulin, and synaptic actin pathways. These transcriptional networks show parallels to ASD and SCHZ, highlighting shared mechanisms across social behavior disorders.\"\n", "!Series_overall_design\t\"Human lymphoblastoid cells immortailzed from WIlliams syndrome patients and non-affected parental controls were grown in RMPI 1640 with 10% FBS, 5% pen/strep, 5% L-glutamine and 0.5% gentamycin. Total RNA was extracted from each culture using the Qiagen RNeasy kit with DNase digestion. Prior to labeling, ribosomal RNA was removed from total RNA (1 μg per sample) using the RiboMinus Human/Mouse Transcriptome Isolation Kit (Invitrogen). Expression analysis was conducted using Affymetrix Human Exon 1.0 ST arrays following the Affymetrix hybridization protocols. Exon expression data were analyzed through Affymetrix Expression Console using exon- and gene-level PLIER (Affymetrix Power Tool with PM-GCBG background correction) summarization and sketch-quantile normalization methods.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['disease state: unaffected parental control', 'disease state: Williams syndrome patient']}\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": "e197439e", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "cee155c9", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:07:46.724772Z", "iopub.status.busy": "2025-03-25T07:07:46.724670Z", "iopub.status.idle": "2025-03-25T07:07:46.731146Z", "shell.execute_reply": "2025-03-25T07:07:46.730855Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Clinical Data Preview:\n", "{0: [0.0]}\n", "Clinical data saved to ../../output/preprocess/Cardiovascular_Disease/clinical_data/GSE285666.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 background info, this dataset contains gene expression data from Affymetrix Human Exon 1.0 ST arrays\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "\n", "# 2.1 Data Availability\n", "# The sample characteristics dictionary shows only one entry at key 0:\n", "# It contains 'disease state' with two values: 'unaffected parental control' and 'Williams syndrome patient'\n", "# This can be used for our trait (Cardiovascular_Disease)\n", "trait_row = 0 # 'disease state' is at key 0\n", "age_row = None # No age information available\n", "gender_row = None # No gender information available\n", "\n", "# 2.2 Data Type Conversion Functions\n", "\n", "def convert_trait(value: str) -> int:\n", " \"\"\"Convert disease state to binary trait value for Cardiovascular_Disease.\n", " Williams syndrome is associated with cardiovascular abnormalities.\"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract value after colon if present\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Convert to binary: Williams syndrome patients are the cases (1), controls are (0)\n", " if 'williams syndrome patient' in value.lower():\n", " return 1\n", " elif 'unaffected' in value.lower() or 'control' in value.lower():\n", " return 0\n", " else:\n", " return None\n", "\n", "def convert_age(value: str) -> Optional[float]:\n", " \"\"\"Convert age information to numeric value.\"\"\"\n", " # Not used as age data is not available\n", " return None\n", "\n", "def convert_gender(value: str) -> Optional[int]:\n", " \"\"\"Convert gender information to binary (0: female, 1: male).\"\"\"\n", " # Not used as gender data is not available\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Determine trait availability based on trait_row\n", "is_trait_available = trait_row is not None\n", "\n", "# Validate and save initial cohort info\n", "validate_and_save_cohort_info(\n", " is_final=False,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=is_gene_available,\n", " is_trait_available=is_trait_available\n", ")\n", "\n", "# 4. Clinical Feature Extraction\n", "if trait_row is not None:\n", " # Create a DataFrame from the sample characteristics dictionary\n", " clinical_data = pd.DataFrame({0: ['disease state: unaffected parental control', \n", " 'disease state: Williams syndrome patient']})\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 selected clinical data\n", " preview = preview_df(selected_clinical_df)\n", " print(\"Clinical Data Preview:\")\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 the selected clinical features to a CSV file\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": "4b5b9ce1", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "febccfed", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:07:46.732143Z", "iopub.status.busy": "2025-03-25T07:07:46.732043Z", "iopub.status.idle": "2025-03-25T07:07:46.864460Z", "shell.execute_reply": "2025-03-25T07:07:46.864096Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Matrix file found: ../../input/GEO/Cardiovascular_Disease/GSE285666/GSE285666_series_matrix.txt.gz\n", "Gene data shape: (22011, 52)\n", "First 20 gene/probe identifiers:\n", "Index(['2315554', '2315633', '2315674', '2315739', '2315894', '2315918',\n", " '2315951', '2316218', '2316245', '2316379', '2316558', '2316605',\n", " '2316746', '2316905', '2316953', '2317246', '2317317', '2317434',\n", " '2317472', '2317512'],\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": "60d8ecf3", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "e014d312", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:07:46.865737Z", "iopub.status.busy": "2025-03-25T07:07:46.865623Z", "iopub.status.idle": "2025-03-25T07:07:46.867502Z", "shell.execute_reply": "2025-03-25T07:07:46.867224Z" } }, "outputs": [], "source": [ "# Examining the gene identifiers\n", "# These appear to be probe IDs or numerical identifiers, not standard human gene symbols\n", "# Human gene symbols typically follow a pattern like GAPDH, TP53, etc.\n", "# These numerical identifiers will need to be mapped to human gene symbols\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "f961f2e2", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "4bf874e6", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:07:46.868631Z", "iopub.status.busy": "2025-03-25T07:07:46.868530Z", "iopub.status.idle": "2025-03-25T07:07:50.557096Z", "shell.execute_reply": "2025-03-25T07:07:50.556446Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene annotation preview:\n", "Columns in gene annotation: ['ID', 'GB_LIST', 'SPOT_ID', 'seqname', 'RANGE_GB', 'RANGE_STRAND', 'RANGE_START', 'RANGE_STOP', 'total_probes', 'gene_assignment', 'mrna_assignment', 'category']\n", "{'ID': ['2315100', '2315106', '2315109', '2315111', '2315113'], 'GB_LIST': ['NR_024005,NR_034090,NR_024004,AK093685', 'DQ786314', nan, nan, 'DQ786265'], 'SPOT_ID': ['chr1:11884-14409', 'chr1:14760-15198', 'chr1:19408-19712', 'chr1:25142-25532', 'chr1:27563-27813'], 'seqname': ['chr1', 'chr1', 'chr1', 'chr1', 'chr1'], 'RANGE_GB': ['NC_000001.10', 'NC_000001.10', 'NC_000001.10', 'NC_000001.10', 'NC_000001.10'], 'RANGE_STRAND': ['+', '+', '+', '+', '+'], 'RANGE_START': ['11884', '14760', '19408', '25142', '27563'], 'RANGE_STOP': ['14409', '15198', '19712', '25532', '27813'], 'total_probes': ['20', '8', '4', '4', '4'], 'gene_assignment': ['NR_024005 // DDX11L2 // DEAD/H (Asp-Glu-Ala-Asp/His) box polypeptide 11 like 2 // 2q13 // 84771 /// NR_034090 // DDX11L9 // DEAD/H (Asp-Glu-Ala-Asp/His) box polypeptide 11 like 9 // 15q26.3 // 100288486 /// NR_024004 // DDX11L2 // DEAD/H (Asp-Glu-Ala-Asp/His) box polypeptide 11 like 2 // 2q13 // 84771 /// AK093685 // DDX11L2 // DEAD/H (Asp-Glu-Ala-Asp/His) box polypeptide 11 like 2 // 2q13 // 84771', '---', '---', '---', '---'], 'mrna_assignment': ['NR_024005 // RefSeq // Homo sapiens DEAD/H (Asp-Glu-Ala-Asp/His) box polypeptide 11 like 2 (DDX11L2), transcript variant 2, non-coding RNA. // chr1 // 100 // 80 // 16 // 16 // 0 /// NR_034090 // RefSeq // Homo sapiens DEAD/H (Asp-Glu-Ala-Asp/His) box polypeptide 11 like 9 (DDX11L9), non-coding RNA. // chr1 // 100 // 80 // 16 // 16 // 0 /// NR_024004 // RefSeq // Homo sapiens DEAD/H (Asp-Glu-Ala-Asp/His) box polypeptide 11 like 2 (DDX11L2), transcript variant 1, non-coding RNA. // chr1 // 100 // 75 // 15 // 15 // 0 /// AK093685 // GenBank // Homo sapiens cDNA FLJ36366 fis, clone THYMU2007824. // chr1 // 94 // 80 // 15 // 16 // 0 /// ENST00000513886 // ENSEMBL // cdna:known chromosome:GRCh37:16:61555:64090:1 gene:ENSG00000233614 // chr1 // 100 // 80 // 16 // 16 // 0 /// ENST00000456328 // ENSEMBL // cdna:known chromosome:GRCh37:1:11869:14409:1 gene:ENSG00000223972 // chr1 // 100 // 80 // 16 // 16 // 0 /// ENST00000518655 // ENSEMBL // cdna:known chromosome:GRCh37:1:11869:14409:1 gene:ENSG00000253101 // chr1 // 100 // 80 // 16 // 16 // 0', 'DQ786314 // GenBank // Homo sapiens clone HLS_IMAGE_811138 mRNA sequence. // chr1 // 100 // 38 // 3 // 3 // 0', '---', '---', 'DQ786265 // GenBank // Homo sapiens clone HLS_IMAGE_298685 mRNA sequence. // chr1 // 100 // 100 // 4 // 4 // 0'], 'category': ['main', 'main', '---', '---', 'main']}\n", "\n", "Searching for platform information in SOFT file:\n", "!Series_platform_id = GPL5175\n", "\n", "Searching for gene symbol information in SOFT file:\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "No explicit gene symbol references found in first 1000 lines\n", "\n", "Checking for additional annotation files in the directory:\n", "[]\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", "# Let's look for platform information in the SOFT file to understand the annotation better\n", "print(\"\\nSearching for platform information in SOFT file:\")\n", "with gzip.open(soft_file, 'rt') as f:\n", " for i, line in enumerate(f):\n", " if '!Series_platform_id' in line:\n", " print(line.strip())\n", " break\n", " if i > 100: # Limit search to first 100 lines\n", " print(\"Platform ID not found in first 100 lines\")\n", " break\n", "\n", "# Check if the SOFT file includes any reference to gene symbols\n", "print(\"\\nSearching for gene symbol information in SOFT file:\")\n", "with gzip.open(soft_file, 'rt') as f:\n", " gene_symbol_lines = []\n", " for i, line in enumerate(f):\n", " if 'GENE_SYMBOL' in line or 'gene_symbol' in line.lower() or 'symbol' in line.lower():\n", " gene_symbol_lines.append(line.strip())\n", " if i > 1000 and len(gene_symbol_lines) > 0: # Limit search but ensure we found something\n", " break\n", " \n", " if gene_symbol_lines:\n", " print(\"Found references to gene symbols:\")\n", " for line in gene_symbol_lines[:5]: # Show just first 5 matches\n", " print(line)\n", " else:\n", " print(\"No explicit gene symbol references found in first 1000 lines\")\n", "\n", "# Look for alternative annotation files or references in the directory\n", "print(\"\\nChecking for additional annotation files in the directory:\")\n", "all_files = os.listdir(in_cohort_dir)\n", "print([f for f in all_files if 'annotation' in f.lower() or 'platform' in f.lower() or 'gpl' in f.lower()])\n" ] }, { "cell_type": "markdown", "id": "abc75a89", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "a9dd4f22", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:07:50.558923Z", "iopub.status.busy": "2025-03-25T07:07:50.558796Z", "iopub.status.idle": "2025-03-25T07:07:52.740087Z", "shell.execute_reply": "2025-03-25T07:07:52.739428Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Creating gene mapping...\n", "Initial mapping shape: (316481, 2)\n", "\n", "Mapping data preview:\n", "{'ID': ['2315100', '2315106', '2315109', '2315111', '2315113'], 'Gene': ['NR_024005 // DDX11L2 // DEAD/H (Asp-Glu-Ala-Asp/His) box polypeptide 11 like 2 // 2q13 // 84771 /// NR_034090 // DDX11L9 // DEAD/H (Asp-Glu-Ala-Asp/His) box polypeptide 11 like 9 // 15q26.3 // 100288486 /// NR_024004 // DDX11L2 // DEAD/H (Asp-Glu-Ala-Asp/His) box polypeptide 11 like 2 // 2q13 // 84771 /// AK093685 // DDX11L2 // DEAD/H (Asp-Glu-Ala-Asp/His) box polypeptide 11 like 2 // 2q13 // 84771', '---', '---', '---', '---']}\n", "\n", "Converting probe-level measurements to gene expression data...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data shape after mapping: (48895, 52)\n", "\n", "First few rows of gene expression data after mapping:\n", " GSM8706502 GSM8706503 GSM8706504 GSM8706505 GSM8706506\n", "Gene \n", "A- 705.687242 644.757871 530.848969 699.485877 494.625018\n", "A-2 167.820123 141.614092 95.105952 161.367554 89.000033\n", "A-52 3333.508407 3190.445107 3666.979423 3144.687791 3426.421530\n", "A-E 28.445449 39.869927 30.423145 32.999802 35.006814\n", "A-I 486.510110 392.250858 423.991434 436.110931 346.470518\n", "\n", "Sample of gene symbols after mapping:\n", "Index(['A-', 'A-2', 'A-52', 'A-E', 'A-I', 'A-II', 'A-IV', 'A-V', 'A0', 'A1',\n", " 'A1-', 'A10', 'A11', 'A12', 'A13', 'A14', 'A16', 'A1BG', 'A1BG-AS',\n", " 'A1CF'],\n", " dtype='object', name='Gene')\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene expression data saved to ../../output/preprocess/Cardiovascular_Disease/gene_data/GSE285666.csv\n" ] } ], "source": [ "# 1. Identify which columns store the gene identifiers and gene symbols\n", "# From the preview, we can see:\n", "# - 'ID' column contains gene identifiers that match those in gene_data.index\n", "# - 'gene_assignment' column contains gene symbols and annotations\n", "\n", "# First, extract the mapping between probe IDs and gene symbols\n", "print(\"Creating gene mapping...\")\n", "mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='gene_assignment')\n", "print(f\"Initial mapping shape: {mapping_df.shape}\")\n", "\n", "# Preview the mapping data\n", "print(\"\\nMapping data preview:\")\n", "print(preview_df(mapping_df, n=5))\n", "\n", "# 2. Apply the gene mapping to convert probe-level measurements to gene expression data\n", "print(\"\\nConverting probe-level measurements to gene expression data...\")\n", "gene_data = apply_gene_mapping(gene_data, mapping_df)\n", "print(f\"Gene expression data shape after mapping: {gene_data.shape}\")\n", "\n", "# Preview the first few rows of the processed gene expression data\n", "print(\"\\nFirst few rows of gene expression data after mapping:\")\n", "print(gene_data.head().iloc[:, :5]) # Show only first 5 columns for brevity\n", "\n", "# Display a sample of gene symbols after mapping\n", "print(\"\\nSample of gene symbols after mapping:\")\n", "print(gene_data.index[:20])\n", "\n", "# Save the gene expression data to 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\"\\nGene expression data saved to {out_gene_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "da4f159d", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "f3674587", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:07:52.741986Z", "iopub.status.busy": "2025-03-25T07:07:52.741857Z", "iopub.status.idle": "2025-03-25T07:08:02.447385Z", "shell.execute_reply": "2025-03-25T07:08:02.446709Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Original gene data shape: (48895, 52)\n", "Normalized gene data shape: (18418, 52)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data saved to ../../output/preprocess/Cardiovascular_Disease/gene_data/GSE285666.csv\n", "Clinical features shape: (1, 52)\n", "Clinical features preview:\n", "{'GSM8706502': [0.0], 'GSM8706503': [0.0], 'GSM8706504': [0.0], 'GSM8706505': [0.0], 'GSM8706506': [0.0], 'GSM8706507': [0.0], 'GSM8706508': [0.0], 'GSM8706509': [0.0], 'GSM8706510': [0.0], 'GSM8706511': [0.0], 'GSM8706512': [0.0], 'GSM8706513': [0.0], 'GSM8706514': [0.0], 'GSM8706515': [0.0], 'GSM8706516': [0.0], 'GSM8706517': [0.0], 'GSM8706518': [0.0], 'GSM8706519': [0.0], 'GSM8706520': [1.0], 'GSM8706521': [1.0], 'GSM8706522': [1.0], 'GSM8706523': [1.0], 'GSM8706524': [1.0], 'GSM8706525': [1.0], 'GSM8706526': [1.0], 'GSM8706527': [1.0], 'GSM8706528': [1.0], 'GSM8706529': [1.0], 'GSM8706530': [1.0], 'GSM8706531': [1.0], 'GSM8706532': [1.0], 'GSM8706533': [1.0], 'GSM8706534': [1.0], 'GSM8706535': [1.0], 'GSM8706536': [1.0], 'GSM8706537': [1.0], 'GSM8706538': [1.0], 'GSM8706539': [1.0], 'GSM8706540': [1.0], 'GSM8706541': [1.0], 'GSM8706542': [1.0], 'GSM8706543': [1.0], 'GSM8706544': [1.0], 'GSM8706545': [1.0], 'GSM8706546': [1.0], 'GSM8706547': [1.0], 'GSM8706548': [1.0], 'GSM8706549': [1.0], 'GSM8706550': [1.0], 'GSM8706551': [1.0], 'GSM8706552': [1.0], 'GSM8706553': [1.0]}\n", "Clinical data saved to ../../output/preprocess/Cardiovascular_Disease/clinical_data/GSE285666.csv\n", "Linked data shape: (52, 18419)\n", "Linked data preview (first 5 rows, 5 columns):\n", " Cardiovascular_Disease A1BG A1BG-AS1 A1CF \\\n", "GSM8706502 0.0 38.534348 38.534348 53.078847 \n", "GSM8706503 0.0 50.069114 50.069114 44.858291 \n", "GSM8706504 0.0 47.107387 47.107387 53.772984 \n", "GSM8706505 0.0 54.198439 54.198439 49.542268 \n", "GSM8706506 0.0 35.837959 35.837959 63.008107 \n", "\n", " A2M \n", "GSM8706502 106.475358 \n", "GSM8706503 110.093250 \n", "GSM8706504 99.340176 \n", "GSM8706505 125.083757 \n", "GSM8706506 96.761368 \n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data shape after handling missing values: (52, 18419)\n", "For the feature 'Cardiovascular_Disease', the least common label is '0.0' with 18 occurrences. This represents 34.62% of the dataset.\n", "The distribution of the feature 'Cardiovascular_Disease' in this dataset is fine.\n", "\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data saved to ../../output/preprocess/Cardiovascular_Disease/GSE285666.csv\n" ] } ], "source": [ "# 1. Normalize gene symbols\n", "print(f\"Original gene data shape: {gene_data.shape}\")\n", "\n", "try:\n", " # Attempt to normalize gene symbols\n", " gene_data_normalized = normalize_gene_symbols_in_index(gene_data)\n", " print(f\"Normalized gene data shape: {gene_data_normalized.shape}\")\n", "except Exception as e:\n", " print(f\"Gene normalization failed: {e}\")\n", " # If normalization fails, use the original gene data\n", " gene_data_normalized = gene_data.copy()\n", " print(f\"Using original gene data with shape: {gene_data_normalized.shape}\")\n", "\n", "# Save the gene expression data \n", "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", "gene_data_normalized.to_csv(out_gene_data_file)\n", "print(f\"Gene expression data saved to {out_gene_data_file}\")\n", "\n", "# 2. Load the clinical data from Step 2\n", "# Use the clinical_data from previous steps to create the clinical features\n", "# Using the correct trait_row and conversion function from Step 2\n", "def convert_trait(value: str) -> int:\n", " \"\"\"Convert disease state to binary trait value for Cardiovascular_Disease.\n", " Williams syndrome is associated with cardiovascular abnormalities.\"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract value after colon if present\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Convert to binary: Williams syndrome patients are the cases (1), controls are (0)\n", " if 'williams syndrome patient' in value.lower():\n", " return 1\n", " elif 'unaffected' in value.lower() or 'control' in value.lower():\n", " return 0\n", " else:\n", " return None\n", "\n", "# Reload clinical data to ensure we have the correct structure\n", "background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']\n", "clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']\n", "_, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n", "\n", "# Extract clinical features using only the available trait information at row 0\n", "clinical_features = geo_select_clinical_features(\n", " clinical_df=clinical_data, \n", " trait=trait, \n", " trait_row=0, # Using disease state as identified in Step 2\n", " convert_trait=convert_trait,\n", " age_row=None, # No age information available\n", " convert_age=None,\n", " gender_row=None, # No gender information available\n", " convert_gender=None\n", ")\n", "\n", "print(f\"Clinical features shape: {clinical_features.shape}\")\n", "print(\"Clinical features preview:\")\n", "print(preview_df(clinical_features))\n", "\n", "# Save the clinical data\n", "os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", "clinical_features.to_csv(out_clinical_data_file)\n", "print(f\"Clinical data saved to {out_clinical_data_file}\")\n", "\n", "# 3. Link clinical and genetic data\n", "linked_data = geo_link_clinical_genetic_data(clinical_features, gene_data_normalized)\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", "# 4. Handle missing values\n", "linked_data_clean = handle_missing_values(linked_data, trait)\n", "print(f\"Linked data shape after handling missing values: {linked_data_clean.shape}\")\n", "\n", "# 5. Check for bias in the dataset\n", "is_biased, linked_data_clean = judge_and_remove_biased_features(linked_data_clean, trait)\n", "\n", "# 6. Conduct final quality 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=True,\n", " is_trait_available=True,\n", " is_biased=is_biased,\n", " df=linked_data_clean,\n", " note=\"Dataset contains gene expression data from Williams syndrome patients and controls. Williams syndrome is associated with cardiovascular abnormalities.\"\n", ")\n", "\n", "# 7. Save the linked data if it's usable\n", "if is_usable:\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " linked_data_clean.to_csv(out_data_file, index=True)\n", " print(f\"Linked data saved to {out_data_file}\")\n", "else:\n", " print(\"Dataset deemed not usable for associative studies. Linked data not 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 }