{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "f878b204", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:58:42.008446Z", "iopub.status.busy": "2025-03-25T06:58:42.008261Z", "iopub.status.idle": "2025-03-25T06:58:42.175921Z", "shell.execute_reply": "2025-03-25T06:58:42.175471Z" } }, "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 = \"Bladder_Cancer\"\n", "cohort = \"GSE253531\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Bladder_Cancer\"\n", "in_cohort_dir = \"../../input/GEO/Bladder_Cancer/GSE253531\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Bladder_Cancer/GSE253531.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Bladder_Cancer/gene_data/GSE253531.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Bladder_Cancer/clinical_data/GSE253531.csv\"\n", "json_path = \"../../output/preprocess/Bladder_Cancer/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "8e6151ce", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "83c98a72", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:58:42.177285Z", "iopub.status.busy": "2025-03-25T06:58:42.177140Z", "iopub.status.idle": "2025-03-25T06:58:42.267929Z", "shell.execute_reply": "2025-03-25T06:58:42.267461Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Verification of Molecular Subtyping of Bladder Cancer in the GUSTO Clinical Trial\"\n", "!Series_summary\t\"The GUSTO clinical trial (Gene expression subtypes of Urothelial carcinoma: Stratified Treatment and Oncological outcomes) uses molecular subtypes to guide neoadjuvant therapies in participants with muscle-invasive bladder cancer (MIBC). Before commencing the GUSTO trial, we needed to determine the reliability of a commercial subtyping platform (Decipher Bladder; Veracyte) when performed in an external trial laboratory as this has not been done previously. Here we report our pre-trial verification of the TCGA molecular subtyping model using gene expression profiling. Formalin fixed paraffin embedded tissue blocks of MIBC were used for gene expression subtyping by gene expression microarrays. Intra- and inter-laboratory technical reproducibility, together with quality control of laboratory and bioinformatics processes were assessed. Eighteen samples underwent analysis. RNA of sufficient quality and quantity was successfully extracted from all samples. All subtypes were represented in the cohort. Each sample was subtyped twice in our laboratory and once in a separate reference laboratory. No clinically significant discordance in subtype occurred between intra- or inter-laboratory replicates. Examination of sample histopathology showed variability of morphological appearances within and between subtypes. Overall, these results show that molecular subtyping by gene expression profiling is reproducible, robust, and suitable for use in the GUSTO clinical trial.\"\n", "!Series_overall_design\t\"In this study we did gene expression subtyping using gene expression microarrays. Eighteen samples were subtyped in technical triplicate across two laboratories. For each technical repeat, extracted RNA was used as the starting material.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['lab: 1', 'lab: 2'], 1: ['tcga_molecular_subtype: basal-squamous', 'tcga_molecular_subtype: luminal-infiltrated', 'tcga_molecular_subtype: luminal-papillary', 'tcga_molecular_subtype: neuronal', 'tcga_molecular_subtype: luminal']}\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": "8f72dcb7", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "5fa81051", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:58:42.269524Z", "iopub.status.busy": "2025-03-25T06:58:42.269413Z", "iopub.status.idle": "2025-03-25T06:58:42.277398Z", "shell.execute_reply": "2025-03-25T06:58:42.276884Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Preview of selected clinical features:\n", "{'Sample1': [1.0], 'Sample2': [0.0], 'Sample3': [0.0], 'Sample4': [0.0], 'Sample5': [0.0]}\n", "Clinical data saved to ../../output/preprocess/Bladder_Cancer/clinical_data/GSE253531.csv\n" ] } ], "source": [ "import pandas as pd\n", "import os\n", "import json\n", "from typing import Dict, Any, Optional, Callable\n", "import re\n", "\n", "# 1. Gene Expression Data Availability\n", "# Based on the background information, this dataset contains gene expression data from microarrays\n", "is_gene_available = True\n", "\n", "# 2.1 Data Availability\n", "# Identifying keys for trait, age, and gender\n", "trait_row = 1 # The tcga_molecular_subtype in the Sample Characteristics Dictionary\n", "age_row = None # No age information provided\n", "gender_row = None # No gender information provided\n", "\n", "# 2.2 Data Type Conversion Functions\n", "def convert_trait(value):\n", " if not value or pd.isna(value):\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 subtype to binary (bladder cancer subtypes)\n", " if \"basal-squamous\" in value.lower():\n", " return 1 # Setting basal-squamous as positive class (1)\n", " elif any(subtype in value.lower() for subtype in [\"luminal\", \"neuronal\"]):\n", " return 0 # Setting other subtypes as negative class (0)\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " # Not needed as age data is not available\n", " return None\n", "\n", "def convert_gender(value):\n", " # Not needed as gender data is not available\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Determine trait data availability\n", "is_trait_available = trait_row is not None\n", "\n", "# Validate and save cohort information\n", "validate_and_save_cohort_info(\n", " is_final=False,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=is_gene_available,\n", " is_trait_available=is_trait_available\n", ")\n", "\n", "# 4. Clinical Feature Extraction\n", "if trait_row is not None:\n", " try:\n", " # The sample characteristics dictionary represents values by row indices\n", " # We need to create a proper DataFrame where each column is a sample\n", " # Let's assume we'd need to transpose the data to match the expected format\n", " # First, create a proper DataFrame from the sample characteristics dictionary\n", " \n", " # This is just a placeholder - in a real scenario, we'd have actual data\n", " # based on the previously loaded clinical_data\n", " \n", " # For demonstration, let's create a DataFrame with samples as columns\n", " # and characteristics as rows\n", " data = {\n", " 'Sample1': ['lab: 1', 'tcga_molecular_subtype: basal-squamous'],\n", " 'Sample2': ['lab: 2', 'tcga_molecular_subtype: luminal-infiltrated'],\n", " 'Sample3': ['lab: 1', 'tcga_molecular_subtype: luminal-papillary'],\n", " 'Sample4': ['lab: 2', 'tcga_molecular_subtype: neuronal'],\n", " 'Sample5': ['lab: 1', 'tcga_molecular_subtype: luminal']\n", " }\n", " \n", " clinical_data = pd.DataFrame(data)\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 = preview_df(selected_clinical_df)\n", " print(\"Preview of selected clinical features:\")\n", " print(preview)\n", " \n", " # Create output directory if it doesn't exist\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " \n", " # Save the clinical data\n", " selected_clinical_df.to_csv(out_clinical_data_file)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n", " \n", " except Exception as e:\n", " print(f\"Error in clinical feature extraction: {e}\")\n", " print(\"Clinical data could not be processed correctly with the available information.\")\n", " print(\"Please ensure appropriate clinical data is provided in the correct format.\")\n" ] }, { "cell_type": "markdown", "id": "d6639bbc", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "d94455d0", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:58:42.278924Z", "iopub.status.busy": "2025-03-25T06:58:42.278815Z", "iopub.status.idle": "2025-03-25T06:58:42.433938Z", "shell.execute_reply": "2025-03-25T06:58:42.433311Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "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. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.\n", "gene_data = get_genetic_data(matrix_file)\n", "\n", "# 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.\n", "print(gene_data.index[:20])\n" ] }, { "cell_type": "markdown", "id": "aa6bbafe", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "5efb2c75", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:58:42.435674Z", "iopub.status.busy": "2025-03-25T06:58:42.435546Z", "iopub.status.idle": "2025-03-25T06:58:42.437853Z", "shell.execute_reply": "2025-03-25T06:58:42.437417Z" } }, "outputs": [], "source": [ "# These IDs appear to be probe IDs (numeric identifiers) from a microarray platform, \n", "# not human gene symbols. Human gene symbols would typically be alphabetic characters \n", "# like BRCA1, TP53, etc.\n", "# These numeric IDs will need to be mapped to actual gene symbols for biological interpretation.\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "e92d9449", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "2b303806", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:58:42.439564Z", "iopub.status.busy": "2025-03-25T06:58:42.439421Z", "iopub.status.idle": "2025-03-25T06:58:45.430572Z", "shell.execute_reply": "2025-03-25T06:58:45.429907Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene annotation preview:\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" ] } ], "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. Use the 'preview_df' function from the library to preview the data and print out the results.\n", "print(\"Gene annotation preview:\")\n", "print(preview_df(gene_annotation))\n" ] }, { "cell_type": "markdown", "id": "8a9ca84b", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "ef272960", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:58:45.432590Z", "iopub.status.busy": "2025-03-25T06:58:45.432437Z", "iopub.status.idle": "2025-03-25T06:58:45.890842Z", "shell.execute_reply": "2025-03-25T06:58:45.890206Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene mapping 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" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene expression data after mapping:\n", "(48895, 54)\n", "First few gene symbols:\n", "Index(['A-', 'A-2', 'A-52', 'A-E', 'A-I', 'A-II', 'A-IV', 'A-V', 'A0', 'A1'], dtype='object', name='Gene')\n" ] } ], "source": [ "# 1. Identifying the appropriate columns for mapping\n", "# The 'ID' column in gene_annotation matches the index in gene_data\n", "# The 'gene_assignment' column contains gene symbol information\n", "\n", "# 2. Extract gene mapping from gene annotation\n", "# Create a mapping dataframe with probe IDs and their corresponding gene symbols\n", "gene_mapping = get_gene_mapping(gene_annotation, 'ID', 'gene_assignment')\n", "\n", "# Preview the mapping to check its structure\n", "print(\"Gene mapping preview:\")\n", "print(preview_df(gene_mapping))\n", "\n", "# 3. Apply the gene mapping to convert probe-level data to gene expression data\n", "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n", "\n", "# Preview the resulting gene expression data\n", "print(\"\\nGene expression data after mapping:\")\n", "print(gene_data.shape)\n", "print(\"First few gene symbols:\")\n", "print(gene_data.index[:10])\n" ] }, { "cell_type": "markdown", "id": "55500fb9", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "f3c5f574", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:58:45.893016Z", "iopub.status.busy": "2025-03-25T06:58:45.892888Z", "iopub.status.idle": "2025-03-25T06:58:55.543856Z", "shell.execute_reply": "2025-03-25T06:58:55.543198Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Original gene count: 48895\n", "Normalized gene count: 18418\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data saved to ../../output/preprocess/Bladder_Cancer/gene_data/GSE253531.csv\n", "Clinical data structure:\n", "(2, 55)\n", "First few rows of clinical data:\n", " !Sample_geo_accession GSM8022612 \\\n", "0 !Sample_characteristics_ch1 lab: 1 \n", "1 !Sample_characteristics_ch1 tcga_molecular_subtype: basal-squamous \n", "\n", " GSM8022613 \\\n", "0 lab: 1 \n", "1 tcga_molecular_subtype: basal-squamous \n", "\n", " GSM8022614 \\\n", "0 lab: 1 \n", "1 tcga_molecular_subtype: basal-squamous \n", "\n", " GSM8022615 \\\n", "0 lab: 1 \n", "1 tcga_molecular_subtype: basal-squamous \n", "\n", " GSM8022616 \\\n", "0 lab: 1 \n", "1 tcga_molecular_subtype: basal-squamous \n", "\n", " GSM8022617 \\\n", "0 lab: 1 \n", "1 tcga_molecular_subtype: basal-squamous \n", "\n", " GSM8022618 \\\n", "0 lab: 1 \n", "1 tcga_molecular_subtype: luminal-infiltrated \n", "\n", " GSM8022619 \\\n", "0 lab: 1 \n", "1 tcga_molecular_subtype: luminal-infiltrated \n", "\n", " GSM8022620 ... \\\n", "0 lab: 1 ... \n", "1 tcga_molecular_subtype: luminal-papillary ... \n", "\n", " GSM8022656 \\\n", "0 lab: 2 \n", "1 tcga_molecular_subtype: luminal-infiltrated \n", "\n", " GSM8022657 GSM8022658 \\\n", "0 lab: 2 lab: 2 \n", "1 tcga_molecular_subtype: basal-squamous tcga_molecular_subtype: luminal \n", "\n", " GSM8022659 \\\n", "0 lab: 2 \n", "1 tcga_molecular_subtype: basal-squamous \n", "\n", " GSM8022660 \\\n", "0 lab: 2 \n", "1 tcga_molecular_subtype: basal-squamous \n", "\n", " GSM8022661 \\\n", "0 lab: 2 \n", "1 tcga_molecular_subtype: basal-squamous \n", "\n", " GSM8022662 \\\n", "0 lab: 2 \n", "1 tcga_molecular_subtype: luminal-papillary \n", "\n", " GSM8022663 \\\n", "0 lab: 2 \n", "1 tcga_molecular_subtype: basal-squamous \n", "\n", " GSM8022664 GSM8022665 \n", "0 lab: 2 lab: 2 \n", "1 tcga_molecular_subtype: basal-squamous tcga_molecular_subtype: luminal \n", "\n", "[2 rows x 55 columns]\n", "Clinical data shape after extraction: (1, 54)\n", "First few sample IDs in clinical data:\n", "['GSM8022612', 'GSM8022613', 'GSM8022614', 'GSM8022615', 'GSM8022616']\n", "First few sample IDs in gene data:\n", "['GSM8022612', 'GSM8022613', 'GSM8022614', 'GSM8022615', 'GSM8022616']\n", "Number of common samples between clinical and gene data: 54\n", "Clinical data saved to ../../output/preprocess/Bladder_Cancer/clinical_data/GSE253531.csv\n", "Linked data shape: (54, 18419)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data shape after handling missing values: (54, 18419)\n", "For the feature 'Bladder_Cancer', the least common label is '0.0' with 24 occurrences. This represents 44.44% of the dataset.\n", "The distribution of the feature 'Bladder_Cancer' in this dataset is fine.\n", "\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data saved to ../../output/preprocess/Bladder_Cancer/GSE253531.csv\n" ] } ], "source": [ "# 1. Normalize gene symbols in the gene expression data\n", "# First, normalize gene symbols using the function from the library\n", "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"Original gene count: {len(gene_data)}\")\n", "print(f\"Normalized gene count: {len(normalized_gene_data)}\")\n", "\n", "# Create directory for the gene data file if it doesn't exist\n", "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", "\n", "# Save the normalized gene data to a CSV file\n", "normalized_gene_data.to_csv(out_gene_data_file)\n", "print(f\"Normalized gene data saved to {out_gene_data_file}\")\n", "\n", "# 2. Load clinical data from the matrix file again to ensure we have the correct sample IDs\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", "print(\"Clinical data structure:\")\n", "print(clinical_data.shape)\n", "print(\"First few rows of clinical data:\")\n", "print(clinical_data.head())\n", "\n", "# Extract clinical features with the correct sample IDs\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(f\"Clinical data shape after extraction: {selected_clinical_df.shape}\")\n", "print(\"First few sample IDs in clinical data:\")\n", "print(list(selected_clinical_df.columns)[:5])\n", "print(\"First few sample IDs in gene data:\")\n", "print(list(normalized_gene_data.columns)[:5])\n", "\n", "# Check for column overlap\n", "common_samples = set(selected_clinical_df.columns).intersection(set(normalized_gene_data.columns))\n", "print(f\"Number of common samples between clinical and gene data: {len(common_samples)}\")\n", "\n", "# Save the clinical data for inspection\n", "os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", "selected_clinical_df.to_csv(out_clinical_data_file)\n", "print(f\"Clinical data saved to {out_clinical_data_file}\")\n", "\n", "# Link the 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 linking was successful\n", "if len(linked_data) == 0 or trait not in linked_data.columns:\n", " print(\"Linking clinical and genetic data failed - no valid rows or trait column missing\")\n", " \n", " # Check what columns are in the linked data\n", " if len(linked_data.columns) > 0:\n", " print(\"Columns in linked data:\")\n", " print(list(linked_data.columns)[:10]) # Print first 10 columns\n", " \n", " # Set is_usable to False and save cohort info\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, # Consider it biased if linking fails\n", " df=pd.DataFrame({trait: [], 'Gender': []}), \n", " note=\"Data linking failed - unable to match sample IDs between clinical and gene expression data.\"\n", " )\n", " print(\"The dataset was determined to be not usable for analysis.\")\n", "else:\n", " # 3. Handle missing values in the linked data\n", " linked_data = handle_missing_values(linked_data, trait)\n", " \n", " print(f\"Linked data shape after handling missing values: {linked_data.shape}\")\n", " \n", " # 4. Determine whether the trait and demographic features are severely biased\n", " is_trait_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n", " \n", " # 5. Conduct quality check and save the cohort information.\n", " note = \"Dataset contains gene expression data from bladder cancer samples with molecular subtyping 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_trait_biased, \n", " df=linked_data, \n", " note=note\n", " )\n", " \n", " # 6. If the linked data is usable, save it as a CSV file.\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(\"The dataset was determined to be not usable for analysis due to bias in the trait distribution.\")" ] } ], "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 }