{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "fc9e2c8c", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:43:12.743629Z", "iopub.status.busy": "2025-03-25T03:43:12.743522Z", "iopub.status.idle": "2025-03-25T03:43:12.919675Z", "shell.execute_reply": "2025-03-25T03:43:12.919298Z" } }, "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 = \"Psoriasis\"\n", "cohort = \"GSE183134\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Psoriasis\"\n", "in_cohort_dir = \"../../input/GEO/Psoriasis/GSE183134\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Psoriasis/GSE183134.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Psoriasis/gene_data/GSE183134.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Psoriasis/clinical_data/GSE183134.csv\"\n", "json_path = \"../../output/preprocess/Psoriasis/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "53975da2", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "22e803eb", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:43:12.921238Z", "iopub.status.busy": "2025-03-25T03:43:12.921076Z", "iopub.status.idle": "2025-03-25T03:43:13.026969Z", "shell.execute_reply": "2025-03-25T03:43:13.026605Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Transcriptomic profiling of Pityriasis Rubra Pilaris (PRP) and Psoriasis\"\n", "!Series_summary\t\"The microarray experiment was employed to evaluate the gene expressions in skin lesions of PRP and psoriasis.\"\n", "!Series_overall_design\t\"To investigate the specific gene regulations, microarray profiling was performed on RNA extracted from paraffin embedded skin biopsy samples.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['tissue: Skin'], 1: ['disease state: Pityriasis_Rubra_Pilaris', 'disease state: Psoriasis']}\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": "938c9e97", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "2857c024", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:43:13.028247Z", "iopub.status.busy": "2025-03-25T03:43:13.028130Z", "iopub.status.idle": "2025-03-25T03:43:13.036019Z", "shell.execute_reply": "2025-03-25T03:43:13.035681Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Preview of selected clinical features:\n", "{'GSM5551681': [0.0], 'GSM5551682': [0.0], 'GSM5551683': [0.0], 'GSM5551684': [0.0], 'GSM5551685': [0.0], 'GSM5551686': [0.0], 'GSM5551687': [0.0], 'GSM5551688': [0.0], 'GSM5551689': [0.0], 'GSM5551690': [0.0], 'GSM5551691': [0.0], 'GSM5551692': [0.0], 'GSM5551693': [0.0], 'GSM5551694': [1.0], 'GSM5551695': [1.0], 'GSM5551696': [1.0], 'GSM5551697': [1.0], 'GSM5551698': [1.0], 'GSM5551699': [1.0], 'GSM5551700': [1.0], 'GSM5551701': [1.0], 'GSM5551702': [1.0], 'GSM5551703': [1.0], 'GSM5551704': [1.0], 'GSM5551705': [1.0], 'GSM5551706': [1.0], 'GSM5551707': [1.0], 'GSM5551708': [1.0], 'GSM5551709': [1.0], 'GSM5551710': [1.0], 'GSM5551711': [1.0], 'GSM5551712': [1.0], 'GSM5551713': [1.0], 'GSM5551714': [1.0], 'GSM5551715': [1.0]}\n", "Clinical data saved to ../../output/preprocess/Psoriasis/clinical_data/GSE183134.csv\n" ] } ], "source": [ "# 1. Gene Expression Data Availability\n", "# Based on the background information, this is a microarray profiling study,\n", "# so it likely contains gene expression data\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "# Checking the Sample Characteristics Dictionary\n", "# The trait data (disease state) is available in row 1\n", "trait_row = 1\n", "# No age information is available\n", "age_row = None\n", "# No gender information is available\n", "gender_row = None\n", "\n", "# 2.2 Data Type Conversion\n", "def convert_trait(value):\n", " \"\"\"Convert trait value to binary format (0 for PRP, 1 for Psoriasis)\"\"\"\n", " if value is None:\n", " return None\n", " # Extract the value part if it contains a colon\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " # Convert to binary (1 for Psoriasis, 0 for PRP)\n", " if \"psoriasis\" in value.lower():\n", " return 1\n", " elif \"pityriasis_rubra_pilaris\" in value.lower() or \"prp\" in value.lower():\n", " return 0\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age value to numeric format\"\"\"\n", " # Not needed as age data is not available\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender value to binary format (0 for female, 1 for male)\"\"\"\n", " # Not needed as gender data is not available\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", "# Initial validation\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 data is available, extract clinical features\n", "if trait_row is not None:\n", " # Assuming clinical_data is already defined from previous step\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 to CSV\n", " selected_clinical_df.to_csv(out_clinical_data_file)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "1a54da4e", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "ec02a445", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:43:13.037267Z", "iopub.status.busy": "2025-03-25T03:43:13.037125Z", "iopub.status.idle": "2025-03-25T03:43:13.169686Z", "shell.execute_reply": "2025-03-25T03:43:13.169350Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "First 20 gene/probe identifiers:\n", "Index(['1-Dec', '1-Sep', '10-Mar', '10-Sep', '11-Mar', '11-Sep', '12-Sep',\n", " '14-Sep', '15-Sep', '2-Sep', '3-Mar', '3-Sep', '4-Mar', '4-Sep',\n", " '5-Mar', '6-Mar', '6-Sep', '7-Mar', '7-Sep', '8-Mar'],\n", " dtype='object', name='ID')\n", "\n", "Gene data dimensions: 29405 genes × 35 samples\n" ] } ], "source": [ "# 1. Re-identify the SOFT and matrix files to ensure we have the correct paths\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# 2. Extract the gene expression data from the matrix file\n", "gene_data = get_genetic_data(matrix_file)\n", "\n", "# 3. Print the first 20 row IDs (gene or probe identifiers)\n", "print(\"\\nFirst 20 gene/probe identifiers:\")\n", "print(gene_data.index[:20])\n", "\n", "# 4. Print the dimensions of the gene expression data\n", "print(f\"\\nGene data dimensions: {gene_data.shape[0]} genes × {gene_data.shape[1]} samples\")\n", "\n", "# Note: we keep is_gene_available as True since we successfully extracted gene expression data\n", "is_gene_available = True\n" ] }, { "cell_type": "markdown", "id": "0bdb63da", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "24473946", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:43:13.170896Z", "iopub.status.busy": "2025-03-25T03:43:13.170781Z", "iopub.status.idle": "2025-03-25T03:43:13.172692Z", "shell.execute_reply": "2025-03-25T03:43:13.172412Z" } }, "outputs": [], "source": [ "# Examine the gene identifiers in the dataset\n", "# The identifiers appear to be non-standard gene symbols (e.g., \"1-Dec\", \"1-Sep\", \"10-Mar\")\n", "# These are likely probe identifiers or some other format that requires mapping to standard gene symbols\n", "\n", "# Based on biomedical knowledge, standard human gene symbols would follow HGNC nomenclature\n", "# Examples of standard gene symbols: BRCA1, TP53, TNF, IL6, etc.\n", "# The identifiers seen here (like \"1-Dec\", \"3-Mar\") don't conform to standard gene symbol conventions\n", "\n", "# These identifiers need to be mapped to standard gene symbols for proper analysis\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "c775aeb6", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "8366578d", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:43:13.173764Z", "iopub.status.busy": "2025-03-25T03:43:13.173660Z", "iopub.status.idle": "2025-03-25T03:43:14.332202Z", "shell.execute_reply": "2025-03-25T03:43:14.331807Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Preview of SOFT file content:\n", "^DATABASE = GeoMiame\n", "!Database_name = Gene Expression Omnibus (GEO)\n", "!Database_institute = NCBI NLM NIH\n", "!Database_web_link = http://www.ncbi.nlm.nih.gov/geo\n", "!Database_email = geo@ncbi.nlm.nih.gov\n", "^SERIES = GSE183134\n", "!Series_title = Transcriptomic profiling of Pityriasis Rubra Pilaris (PRP) and Psoriasis\n", "!Series_geo_accession = GSE183134\n", "!Series_status = Public on Sep 30 2021\n", "!Series_submission_date = Aug 31 2021\n", "!Series_last_update_date = Jan 17 2022\n", "!Series_pubmed_id = 34491907\n", "!Series_summary = The microarray experiment was employed to evaluate the gene expressions in skin lesions of PRP and psoriasis.\n", "!Series_overall_design = To investigate the specific gene regulations, microarray profiling was performed on RNA extracted from paraffin embedded skin biopsy samples.\n", "!Series_type = Expression profiling by array\n", "!Series_contributor = Johann,E,Gudjonsson\n", "!Series_contributor = Lam,C,Tsoi\n", "!Series_sample_id = GSM5551681\n", "!Series_sample_id = GSM5551682\n", "!Series_sample_id = GSM5551683\n", "!Series_sample_id = GSM5551684\n", "...\n", "\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene annotation dataframe using default method:\n", "Shape: (1058615, 2)\n", "Columns: ['ID', 'SPOT_ID']\n", " ID SPOT_ID\n", "0 DDX11L1 DDX11L1\n", "1 MIR1302-2 MIR1302-2\n", "2 OR4F5 OR4F5\n", "\n", "Searching for platform annotation section in SOFT file...\n", "^PLATFORM = GPL30572\n", "!platform_table_begin\n", "ID\tSPOT_ID\n", "DDX11L1\tDDX11L1\n", "MIR1302-2\tMIR1302-2\n", "OR4F5\tOR4F5\n", "LOC100132287\tLOC100132287\n", "LOC105379690\tLOC105379690\n", "OR4F29\tOR4F29\n", "LOC105378947\tLOC105378947\n", "LOC105378580\tLOC105378580\n", "LOC100287934\tLOC100287934\n" ] } ], "source": [ "# 1. First get the file paths using geo_get_relevant_filepaths function\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# 2. Inspect the SOFT file structure to understand the annotation format\n", "# Read the first few lines of the SOFT file to examine its structure\n", "import gzip\n", "print(\"Preview of SOFT file content:\")\n", "with gzip.open(soft_file, 'rt') as f:\n", " for i, line in enumerate(f):\n", " print(line.strip())\n", " if i >= 20: # Print first 20 lines to understand structure\n", " break\n", "print(\"...\\n\")\n", "\n", "# 3. Try different approaches to extract gene annotation data\n", "# First, let's try the default method to see what's actually in the file\n", "gene_annotation = get_gene_annotation(soft_file)\n", "print(\"Gene annotation dataframe using default method:\")\n", "print(f\"Shape: {gene_annotation.shape}\")\n", "print(f\"Columns: {gene_annotation.columns.tolist()}\")\n", "print(gene_annotation.head(3))\n", "\n", "# 4. Check if there's another section in the file that might contain the mapping\n", "# Look for platform annotation information in the SOFT file\n", "print(\"\\nSearching for platform annotation section in SOFT file...\")\n", "with gzip.open(soft_file, 'rt') as f:\n", " platform_lines = []\n", " capture = False\n", " for i, line in enumerate(f):\n", " if \"^PLATFORM\" in line:\n", " capture = True\n", " platform_lines.append(line.strip())\n", " elif capture and line.startswith(\"!platform_table_begin\"):\n", " platform_lines.append(line.strip())\n", " for j in range(10): # Capture the next 10 lines to understand the table structure\n", " try:\n", " platform_line = next(f).strip()\n", " platform_lines.append(platform_line)\n", " except StopIteration:\n", " break\n", " break\n", " \n", " print(\"\\n\".join(platform_lines))\n", "\n", "# Maintain gene availability status as True based on previous steps\n", "is_gene_available = True\n" ] }, { "cell_type": "markdown", "id": "4513f69c", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "b726b7ef", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:43:14.333515Z", "iopub.status.busy": "2025-03-25T03:43:14.333386Z", "iopub.status.idle": "2025-03-25T03:43:16.373895Z", "shell.execute_reply": "2025-03-25T03:43:16.373428Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Platform annotation columns: ['ID', 'SPOT_ID']\n", "First few rows of platform annotation:\n", " ID SPOT_ID\n", "0 DDX11L1 DDX11L1\n", "1 MIR1302-2 MIR1302-2\n", "2 OR4F5 OR4F5\n", "3 LOC100132287 LOC100132287\n", "4 LOC105379690 LOC105379690\n", "Number of matching IDs between expression data and gene_annotation['ID']: 29405\n", "Mapping dataframe shape: (1058580, 2)\n", " ID Gene\n", "0 DDX11L1 DDX11L1\n", "1 MIR1302-2 MIR1302-2\n", "2 OR4F5 OR4F5\n", "3 LOC100132287 LOC100132287\n", "4 LOC105379690 LOC105379690\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Mapped gene expression data shape: (22785, 35)\n", "First few gene symbols: ['A1BG', 'A1BG-AS1', 'A1CF', 'A2M', 'A2M-AS1']\n" ] } ], "source": [ "# 1. Examine both gene identifiers and annotation to determine mapping columns\n", "# From previous steps, we can see:\n", "# - The gene expression data has identifiers like \"1-Dec\", \"1-Sep\", \"10-Mar\" as index\n", "# - The gene annotation data shows columns \"ID\" and \"SPOT_ID\"\n", "\n", "# Since the gene annotation DataFrame doesn't seem to contain our probe identifiers directly,\n", "# we need to extract more detailed annotation from the SOFT file\n", "\n", "# Let's specifically look for the platform annotation that contains our probe IDs\n", "with gzip.open(soft_file, 'rt') as f:\n", " platform_lines = []\n", " capture = False\n", " for line in f:\n", " if \"!platform_table_begin\" in line:\n", " capture = True\n", " continue\n", " elif \"!platform_table_end\" in line:\n", " capture = False\n", " break\n", " elif capture:\n", " platform_lines.append(line.strip())\n", "\n", "# Create a DataFrame from the platform lines if we found data\n", "if platform_lines:\n", " import io\n", " platform_df = pd.read_csv(io.StringIO('\\n'.join(platform_lines)), sep='\\t')\n", " print(f\"Platform annotation columns: {platform_df.columns.tolist()}\")\n", " print(f\"First few rows of platform annotation:\")\n", " print(platform_df.head())\n", "else:\n", " # If we couldn't find proper annotation, create a mapping from the gene expression data\n", " # and annotation we already have\n", " print(\"Could not find detailed probe-to-gene mapping in platform annotation.\")\n", " # We'll proceed with the gene annotation we already extracted\n", "\n", "# 2. Get mapping between gene identifiers and gene symbols\n", "# Based on the output from previous steps, both ID and SPOT_ID columns in gene_annotation\n", "# appear to contain gene symbols. Let's check if either matches our expression data index\n", "\n", "# First, check if any IDs in gene_annotation match the expression data index\n", "matching_ids = len(set(gene_data.index) & set(gene_annotation['ID']))\n", "print(f\"Number of matching IDs between expression data and gene_annotation['ID']: {matching_ids}\")\n", "\n", "# If we didn't find matches, the gene identifiers might be in a different format\n", "# Let's try to extract mapping from additional annotation or metadata\n", "if matching_ids == 0:\n", " print(\"No direct matches found. Creating alternative mapping...\")\n", " \n", " # For this dataset, it appears that the gene identifiers are non-standard, \n", " # but the annotation provides standard gene symbols\n", " # We'll create a simple 1:1 mapping using the annotation we have\n", " \n", " # Create a mapping dataframe where both probe ID and gene symbol are the same\n", " # Since our gene identifiers don't seem to map directly to standard annotations,\n", " # we'll use them as-is and treat them as approximations of gene symbols\n", " mapping_df = pd.DataFrame({\n", " 'ID': gene_data.index,\n", " 'Gene': gene_data.index\n", " })\n", " \n", " print(\"Created mapping with gene identifiers as gene symbols.\")\n", " print(f\"Mapping dataframe shape: {mapping_df.shape}\")\n", " print(mapping_df.head())\n", "else:\n", " # If we found matching IDs, use them for mapping\n", " mapping_df = gene_annotation[['ID', 'SPOT_ID']].rename(columns={'SPOT_ID': 'Gene'})\n", " mapping_df = mapping_df[mapping_df['ID'].isin(gene_data.index)]\n", " print(f\"Mapping dataframe shape: {mapping_df.shape}\")\n", " print(mapping_df.head())\n", "\n", "# 3. Apply the gene mapping to convert probe-level measurements to gene-level expression\n", "gene_data_mapped = apply_gene_mapping(gene_data, mapping_df)\n", "print(f\"Mapped gene expression data shape: {gene_data_mapped.shape}\")\n", "print(f\"First few gene symbols: {list(gene_data_mapped.index[:5])}\")\n", "\n", "# Update gene_data to use the mapped values\n", "gene_data = gene_data_mapped\n", "\n", "# Maintain gene availability status\n", "is_gene_available = True\n" ] }, { "cell_type": "markdown", "id": "eeafc1a6", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "99be8255", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:43:16.375375Z", "iopub.status.busy": "2025-03-25T03:43:16.375261Z", "iopub.status.idle": "2025-03-25T03:43:27.729245Z", "shell.execute_reply": "2025-03-25T03:43:27.728882Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Normalizing gene symbols...\n", "Gene data shape after normalization: 22464 genes × 35 samples\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene expression data saved to ../../output/preprocess/Psoriasis/gene_data/GSE183134.csv\n", "Extracting clinical features from the original source...\n", "Extracted clinical features preview:\n", "{'GSM5551681': [0.0], 'GSM5551682': [0.0], 'GSM5551683': [0.0], 'GSM5551684': [0.0], 'GSM5551685': [0.0], 'GSM5551686': [0.0], 'GSM5551687': [0.0], 'GSM5551688': [0.0], 'GSM5551689': [0.0], 'GSM5551690': [0.0], 'GSM5551691': [0.0], 'GSM5551692': [0.0], 'GSM5551693': [0.0], 'GSM5551694': [1.0], 'GSM5551695': [1.0], 'GSM5551696': [1.0], 'GSM5551697': [1.0], 'GSM5551698': [1.0], 'GSM5551699': [1.0], 'GSM5551700': [1.0], 'GSM5551701': [1.0], 'GSM5551702': [1.0], 'GSM5551703': [1.0], 'GSM5551704': [1.0], 'GSM5551705': [1.0], 'GSM5551706': [1.0], 'GSM5551707': [1.0], 'GSM5551708': [1.0], 'GSM5551709': [1.0], 'GSM5551710': [1.0], 'GSM5551711': [1.0], 'GSM5551712': [1.0], 'GSM5551713': [1.0], 'GSM5551714': [1.0], 'GSM5551715': [1.0]}\n", "Clinical data shape: (1, 35)\n", "Clinical features saved to ../../output/preprocess/Psoriasis/clinical_data/GSE183134.csv\n", "Linking clinical and genetic data...\n", "Linked data shape: (35, 22465)\n", "Handling missing values...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Data shape after handling missing values: (35, 22465)\n", "\n", "Checking for bias in feature variables:\n", "For the feature 'Psoriasis', the least common label is '0.0' with 13 occurrences. This represents 37.14% of the dataset.\n", "The distribution of the feature 'Psoriasis' in this dataset is fine.\n", "\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data saved to ../../output/preprocess/Psoriasis/GSE183134.csv\n", "Final dataset shape: (35, 22465)\n" ] } ], "source": [ "# 1. Check if gene data is available after mapping\n", "if gene_data.shape[0] == 0:\n", " print(\"Error: Gene expression matrix is empty after mapping.\")\n", " # Mark the dataset as not usable due to lack of gene expression data\n", " is_usable = validate_and_save_cohort_info(\n", " is_final=True,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=False, # No usable gene data\n", " is_trait_available=True,\n", " is_biased=True,\n", " df=pd.DataFrame(),\n", " note=\"Failed to map probe IDs to gene symbols. The annotation format may not be compatible with the extraction methods.\"\n", " )\n", " print(\"Dataset deemed not usable due to lack of gene expression data.\")\n", "else:\n", " # Only proceed with normalization if we have gene data\n", " print(\"Normalizing gene symbols...\")\n", " gene_data_normalized = normalize_gene_symbols_in_index(gene_data)\n", " print(f\"Gene data shape after normalization: {gene_data_normalized.shape[0]} genes × {gene_data_normalized.shape[1]} samples\")\n", "\n", " # Save the normalized gene 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\"Normalized gene expression data saved to {out_gene_data_file}\")\n", " \n", " # Extract clinical features from the original data source\n", " print(\"Extracting clinical features from the original source...\")\n", " # Get background information and clinical data again\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", " # 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", " print(\"Extracted clinical features preview:\")\n", " print(preview_df(selected_clinical_df))\n", " print(f\"Clinical data shape: {selected_clinical_df.shape}\")\n", " \n", " # Save the extracted clinical features\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 features saved to {out_clinical_data_file}\")\n", " \n", " # Link clinical and genetic data\n", " print(\"Linking clinical and genetic data...\")\n", " linked_data = geo_link_clinical_genetic_data(selected_clinical_df, gene_data_normalized)\n", " print(f\"Linked data shape: {linked_data.shape}\")\n", " \n", " # Check if the linked data has adequate data\n", " if linked_data.shape[0] == 0 or linked_data.shape[1] <= 4: # 4 is an arbitrary small number\n", " print(\"Error: Linked data has insufficient samples or features.\")\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=True,\n", " df=linked_data,\n", " note=\"Failed to properly link gene expression data with clinical features.\"\n", " )\n", " print(\"Dataset deemed not usable due to linking failure.\")\n", " else:\n", " # Handle missing values systematically\n", " print(\"Handling missing values...\")\n", " linked_data_clean = handle_missing_values(linked_data, trait_col=trait)\n", " print(f\"Data shape after handling missing values: {linked_data_clean.shape}\")\n", " \n", " # Check if there are still samples after missing value handling\n", " if linked_data_clean.shape[0] == 0:\n", " print(\"Error: No samples remain after handling missing values.\")\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=True,\n", " df=pd.DataFrame(),\n", " note=\"All samples were removed during missing value handling.\"\n", " )\n", " print(\"Dataset deemed not usable as all samples were filtered out.\")\n", " else:\n", " # Check if the dataset is biased\n", " print(\"\\nChecking for bias in feature variables:\")\n", " is_biased, linked_data_final = judge_and_remove_biased_features(linked_data_clean, trait)\n", " \n", " # 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_final,\n", " note=\"Dataset contains gene expression data for Crohn's Disease patients, examining response to Infliximab treatment.\"\n", " )\n", " \n", " # Save linked data if usable\n", " if is_usable:\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " linked_data_final.to_csv(out_data_file)\n", " print(f\"Linked data saved to {out_data_file}\")\n", " print(f\"Final dataset shape: {linked_data_final.shape}\")\n", " else:\n", " print(\"Dataset deemed not usable for trait association 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 }