{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "1d7255ba", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:41:19.638297Z", "iopub.status.busy": "2025-03-25T08:41:19.638192Z", "iopub.status.idle": "2025-03-25T08:41:19.799754Z", "shell.execute_reply": "2025-03-25T08:41:19.799389Z" } }, "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 = \"Eczema\"\n", "cohort = \"GSE57225\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Eczema\"\n", "in_cohort_dir = \"../../input/GEO/Eczema/GSE57225\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Eczema/GSE57225.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Eczema/gene_data/GSE57225.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Eczema/clinical_data/GSE57225.csv\"\n", "json_path = \"../../output/preprocess/Eczema/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "cb945e6f", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "37297bf6", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:41:19.801181Z", "iopub.status.busy": "2025-03-25T08:41:19.801042Z", "iopub.status.idle": "2025-03-25T08:41:19.982983Z", "shell.execute_reply": "2025-03-25T08:41:19.982655Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Intra-individual genome expression analysis reveals a specific molecular signature of psoriasis and eczema\"\n", "!Series_summary\t\"Comparing molecular signatures of psoriasis and eczema in patients co-affected by both diseases provides a comprehensive understanding of disease pathogenesis as well as a diagnostic tool to differentiate these widespread inflammatory skin diseases.\"\n", "!Series_overall_design\t\"In patients affected by both psoriasis and non-atopic or atopic eczema simultaneously (n=24), whole genome expression arrays of psoriasis, eczema, and non-involved skin were performed\"\n", "!Series_overall_design\t\"Arrays MQ_35 and MQ_41 did not pass quality control and thus were not normalized and were excluded from this Series.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['individual: EP', 'individual: KK', 'individual: KP', 'individual: SI', 'individual: MM', 'individual: ZA', 'individual: LA', 'individual: MOF', 'individual: Mattes', 'individual: SS2', 'individual: Klose', 'individual: JB', 'individual: LI', 'individual: HI', 'individual: SM', 'individual: BC', 'individual: BS (31y)', 'individual: VI', 'individual: BA', 'individual: BS (33y)', 'individual: SP', 'individual: MPG', 'individual: WP'], 1: ['disease state: psoriasis', 'disease state: eczema', 'disease state: control (non-involved)'], 2: ['tissue: skin'], 3: ['gender: male', 'gender: female'], 4: ['age: 48y', 'age: 40y', 'age: 65y', 'age: 35y', 'age: 27y', 'age: 72y', 'age: 33y', 'age: 58y', 'age: 56y', 'age: 46y', 'age: 55y', 'age: 53y', 'age: 31y', 'age: 42y', 'age: 43y', 'age: 20y', 'age: 41y']}\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": "4ec2038b", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "23a31134", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:41:19.984261Z", "iopub.status.busy": "2025-03-25T08:41:19.984147Z", "iopub.status.idle": "2025-03-25T08:41:19.990574Z", "shell.execute_reply": "2025-03-25T08:41:19.990258Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Review of Sample Characteristics Dictionary:\n", "Key 0: ['individual: EP', 'individual: KK', 'individual: KP', 'individual: SI', 'individual: MM', 'individual: ZA', 'individual: LA', 'individual: MOF', 'individual: Mattes', 'individual: SS2', 'individual: Klose', 'individual: JB', 'individual: LI', 'individual: HI', 'individual: SM', 'individual: BC', 'individual: BS (31y)', 'individual: VI', 'individual: BA', 'individual: BS (33y)', 'individual: SP', 'individual: MPG', 'individual: WP']\n", "Key 1: ['disease state: psoriasis', 'disease state: eczema', 'disease state: control (non-involved)']\n", "Key 2: ['tissue: skin']\n", "Key 3: ['gender: male', 'gender: female']\n", "Key 4: ['age: 48y', 'age: 40y', 'age: 65y', 'age: 35y', 'age: 27y', 'age: 72y', 'age: 33y', 'age: 58y', 'age: 56y', 'age: 46y', 'age: 55y', 'age: 53y', 'age: 31y', 'age: 42y', 'age: 43y', 'age: 20y', 'age: 41y']\n", "Note: We have identified that trait, age, and gender data are available in the sample characteristics.\n", "trait_row = 1, age_row = 4, gender_row = 3\n", "However, since we don't have access to the actual clinical data file, we'll skip the data extraction step for now.\n", "The sample characteristics provided are metadata about the unique values, not the actual clinical data.\n" ] } ], "source": [ "import pandas as pd\n", "import os\n", "import json\n", "from typing import Optional, Dict, Any, Callable, List\n", "import re\n", "\n", "# Display sample characteristics to understand the dataset\n", "sample_characteristics = {0: ['individual: EP', 'individual: KK', 'individual: KP', 'individual: SI', 'individual: MM', 'individual: ZA', 'individual: LA', 'individual: MOF', 'individual: Mattes', 'individual: SS2', 'individual: Klose', 'individual: JB', 'individual: LI', 'individual: HI', 'individual: SM', 'individual: BC', 'individual: BS (31y)', 'individual: VI', 'individual: BA', 'individual: BS (33y)', 'individual: SP', 'individual: MPG', 'individual: WP'], 1: ['disease state: psoriasis', 'disease state: eczema', 'disease state: control (non-involved)'], 2: ['tissue: skin'], 3: ['gender: male', 'gender: female'], 4: ['age: 48y', 'age: 40y', 'age: 65y', 'age: 35y', 'age: 27y', 'age: 72y', 'age: 33y', 'age: 58y', 'age: 56y', 'age: 46y', 'age: 55y', 'age: 53y', 'age: 31y', 'age: 42y', 'age: 43y', 'age: 20y', 'age: 41y']}\n", "\n", "print(\"Review of Sample Characteristics Dictionary:\")\n", "for key, values in sample_characteristics.items():\n", " print(f\"Key {key}: {values}\")\n", "\n", "# 1. Gene Expression Data Availability\n", "# Based on the summary and title, this dataset appears to contain genome expression data\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "# From the sample characteristics dictionary:\n", "# Key 1 contains disease state which can be used for our trait (Eczema)\n", "# Key 4 contains age information\n", "# Key 3 contains gender information\n", "trait_row = 1 # 'disease state: psoriasis', 'disease state: eczema', 'disease state: control (non-involved)'\n", "age_row = 4 # Age information is available\n", "gender_row = 3 # Gender information is available\n", "\n", "# 2.2 Data Type Conversion Functions\n", "def convert_trait(value: str) -> Optional[int]:\n", " \"\"\"\n", " Convert trait information to binary format.\n", " 1 for eczema, 0 for control, None for psoriasis (as we're focusing on eczema)\n", " \"\"\"\n", " if value is None:\n", " return None\n", " # Extract value after colon\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " if 'eczema' in value.lower():\n", " return 1 # Case\n", " elif 'control' in value.lower() or 'non-involved' in value.lower():\n", " return 0 # Control\n", " else:\n", " return None # Other conditions like psoriasis\n", "\n", "def convert_age(value: str) -> Optional[float]:\n", " \"\"\"\n", " Convert age information to continuous format.\n", " Extract numeric age value from strings like 'age: 48y'\n", " \"\"\"\n", " if value is None:\n", " return None\n", " # Extract value after colon\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Use regex to extract numbers from the age string\n", " age_match = re.search(r'(\\d+)', value)\n", " if age_match:\n", " return float(age_match.group(1))\n", " return None\n", "\n", "def convert_gender(value: str) -> Optional[int]:\n", " \"\"\"\n", " Convert gender information to binary format.\n", " 0 for female, 1 for male\n", " \"\"\"\n", " if value is None:\n", " return None\n", " # Extract value after colon\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " if 'female' in value.lower():\n", " return 0\n", " elif 'male' in value.lower():\n", " return 1\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Initial filtering on usability - trait data is available if trait_row is not None\n", "is_trait_available = trait_row is not None\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", "# Print a message about clinical data extraction\n", "print(\"Note: We have identified that trait, age, and gender data are available in the sample characteristics.\")\n", "print(f\"trait_row = {trait_row}, age_row = {age_row}, gender_row = {gender_row}\")\n", "print(\"However, since we don't have access to the actual clinical data file, we'll skip the data extraction step for now.\")\n", "print(\"The sample characteristics provided are metadata about the unique values, not the actual clinical data.\")\n" ] }, { "cell_type": "markdown", "id": "32970e1f", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "85a9e393", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:41:19.991752Z", "iopub.status.busy": "2025-03-25T08:41:19.991643Z", "iopub.status.idle": "2025-03-25T08:41:20.279344Z", "shell.execute_reply": "2025-03-25T08:41:20.278975Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Matrix file found: ../../input/GEO/Eczema/GSE57225/GSE57225_series_matrix.txt.gz\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape: (42044, 62)\n", "First 20 gene/probe identifiers:\n", "Index(['A_19_P00315452', 'A_19_P00315459', 'A_19_P00315469', 'A_19_P00315473',\n", " 'A_19_P00315482', 'A_19_P00315490', 'A_19_P00315492', 'A_19_P00315493',\n", " 'A_19_P00315499', 'A_19_P00315502', 'A_19_P00315504', 'A_19_P00315506',\n", " 'A_19_P00315508', 'A_19_P00315518', 'A_19_P00315519', 'A_19_P00315523',\n", " 'A_19_P00315524', 'A_19_P00315526', 'A_19_P00315527', 'A_19_P00315528'],\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": "ccc999c6", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "1dd1070b", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:41:20.280694Z", "iopub.status.busy": "2025-03-25T08:41:20.280577Z", "iopub.status.idle": "2025-03-25T08:41:20.282506Z", "shell.execute_reply": "2025-03-25T08:41:20.282196Z" } }, "outputs": [], "source": [ "# Examining the gene identifiers from the previous step\n", "# These identifiers appear to be Agilent microarray probe IDs (starting with A_19_P),\n", "# not standard human gene symbols (like ACTB, TP53, etc.)\n", "# Therefore, mapping to gene symbols will be required\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "1e202a0e", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "3f2108c6", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:41:20.283618Z", "iopub.status.busy": "2025-03-25T08:41:20.283507Z", "iopub.status.idle": "2025-03-25T08:41:24.869191Z", "shell.execute_reply": "2025-03-25T08:41:24.868817Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene annotation preview:\n", "Columns in gene annotation: ['ID', 'SPOT_ID', 'CONTROL_TYPE', 'REFSEQ', 'GB_ACC', 'GENE', 'GENE_SYMBOL', 'GENE_NAME', 'UNIGENE_ID', 'ENSEMBL_ID', 'TIGR_ID', 'ACCESSION_STRING', 'CHROMOSOMAL_LOCATION', 'CYTOBAND', 'DESCRIPTION', 'GO_ID', 'SEQUENCE']\n", "{'ID': ['(+)E1A_r60_1', '(+)E1A_r60_3', '(+)E1A_r60_a104', '(+)E1A_r60_a107', '(+)E1A_r60_a135'], 'SPOT_ID': ['(+)E1A_r60_1', '(+)E1A_r60_3', '(+)E1A_r60_a104', '(+)E1A_r60_a107', '(+)E1A_r60_a135'], 'CONTROL_TYPE': ['pos', 'pos', 'pos', 'pos', 'pos'], 'REFSEQ': [nan, nan, nan, nan, nan], 'GB_ACC': [nan, nan, nan, nan, nan], 'GENE': [nan, nan, nan, nan, nan], 'GENE_SYMBOL': [nan, nan, nan, nan, nan], 'GENE_NAME': [nan, nan, nan, nan, nan], 'UNIGENE_ID': [nan, nan, nan, nan, nan], 'ENSEMBL_ID': [nan, nan, nan, nan, nan], 'TIGR_ID': [nan, nan, nan, nan, nan], 'ACCESSION_STRING': [nan, nan, nan, nan, nan], 'CHROMOSOMAL_LOCATION': [nan, nan, nan, nan, nan], 'CYTOBAND': [nan, nan, nan, nan, nan], 'DESCRIPTION': [nan, nan, nan, nan, nan], 'GO_ID': [nan, nan, nan, nan, nan], 'SEQUENCE': [nan, nan, nan, nan, nan]}\n", "\n", "Searching for platform information in SOFT file:\n", "!Series_platform_id = GPL14550\n", "\n", "Searching for gene symbol information in SOFT file:\n", "Found references to gene symbols:\n", "#GENE_SYMBOL = Gene Symbol\n", "ID\tSPOT_ID\tCONTROL_TYPE\tREFSEQ\tGB_ACC\tGENE\tGENE_SYMBOL\tGENE_NAME\tUNIGENE_ID\tENSEMBL_ID\tTIGR_ID\tACCESSION_STRING\tCHROMOSOMAL_LOCATION\tCYTOBAND\tDESCRIPTION\tGO_ID\tSEQUENCE\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": "efb3fd1c", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "74cf65d4", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:41:24.870613Z", "iopub.status.busy": "2025-03-25T08:41:24.870486Z", "iopub.status.idle": "2025-03-25T08:41:25.831867Z", "shell.execute_reply": "2025-03-25T08:41:25.831507Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Generated gene mapping dataframe with shape: (30436, 2)\n", "Sample of gene mapping data:\n", " ID Gene\n", "21 A_19_P00315502 XLOC_008373\n", "25 A_19_P00315518 XLOC_005810\n", "26 A_19_P00315519 XLOC_004914\n", "28 A_19_P00315524 XLOC_014192\n", "31 A_19_P00315528 XLOC_008370\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Converted to gene-level expression data with shape: (19725, 62)\n", "Sample of gene expression data:\n", " GSM1377461 GSM1377462 GSM1377463 GSM1377464 GSM1377465 \\\n", "Gene \n", "A1BG 12.977107 13.381272 11.371641 13.209966 12.411935 \n", "A1BG-AS1 6.935017 7.078788 7.111287 7.637369 7.016705 \n", "A1CF 4.846280 5.042712 4.946058 4.353776 5.875778 \n", "A2LD1 8.322505 8.170192 8.379592 8.217080 7.549794 \n", "A2M 11.275092 12.710169 12.025984 12.847757 12.482553 \n", "\n", " GSM1377466 GSM1377467 GSM1377468 GSM1377469 GSM1377470 ... \\\n", "Gene ... \n", "A1BG 13.526912 12.966083 12.651566 13.259562 12.608978 ... \n", "A1BG-AS1 7.483763 7.429407 6.585663 6.524840 6.261774 ... \n", "A1CF 4.998552 5.307923 4.893777 4.880007 4.513105 ... \n", "A2LD1 8.229549 8.247211 7.689971 7.147777 7.747795 ... \n", "A2M 12.976723 12.007616 12.232337 13.135761 12.061959 ... \n", "\n", " GSM1377513 GSM1377514 GSM1377515 GSM1377516 GSM1377517 \\\n", "Gene \n", "A1BG 12.904555 13.239299 14.152031 13.057722 13.466362 \n", "A1BG-AS1 6.082960 6.798525 7.392012 6.645857 6.973300 \n", "A1CF 5.666027 5.453652 6.042744 5.571033 4.275935 \n", "A2LD1 8.431592 7.693956 8.136181 7.384538 7.836907 \n", "A2M 12.878337 12.677917 14.821341 11.462099 12.906260 \n", "\n", " GSM1377518 GSM1377519 GSM1377520 GSM1377521 GSM1377522 \n", "Gene \n", "A1BG 13.159147 13.026104 13.273054 13.253025 12.128323 \n", "A1BG-AS1 7.018946 6.803686 6.649088 7.249076 7.108264 \n", "A1CF 5.635575 5.074816 4.825333 4.871838 4.554325 \n", "A2LD1 7.620271 7.743741 8.041216 7.938968 8.596695 \n", "A2M 11.394855 12.186278 13.044079 13.523840 12.221965 \n", "\n", "[5 rows x 62 columns]\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data saved to: ../../output/preprocess/Eczema/gene_data/GSE57225.csv\n" ] } ], "source": [ "# 1. Determine which columns in the gene annotation contain probe IDs and gene symbols\n", "# Based on the gene annotation preview, the relevant columns are:\n", "# - 'ID': contains probe IDs like those in gene_data.index (A_19_P...)\n", "# - 'GENE_SYMBOL': contains gene symbols\n", "\n", "# 2. Get a gene mapping dataframe with the two relevant columns\n", "gene_mapping = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='GENE_SYMBOL')\n", "print(f\"Generated gene mapping dataframe with shape: {gene_mapping.shape}\")\n", "print(\"Sample of gene mapping data:\")\n", "print(gene_mapping.head())\n", "\n", "# 3. Apply gene mapping to convert probe-level measurements to gene expression data\n", "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n", "print(f\"Converted to gene-level expression data with shape: {gene_data.shape}\")\n", "print(\"Sample of gene expression data:\")\n", "print(gene_data.head())\n", "\n", "# Save the gene 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\"Gene expression data saved to: {out_gene_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "67da6b7e", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "aba6a305", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:41:25.833296Z", "iopub.status.busy": "2025-03-25T08:41:25.833178Z", "iopub.status.idle": "2025-03-25T08:41:34.727691Z", "shell.execute_reply": "2025-03-25T08:41:34.727313Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Checking if clinical data extraction is needed...\n", "Clinical data file not found. Extracting clinical features from original data...\n", "Clinical features extracted and saved to: ../../output/preprocess/Eczema/clinical_data/GSE57225.csv\n", "\n", "Normalizing gene symbols...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape after normalization: (19361, 62)\n", "Sample of normalized gene symbols: ['A1BG', 'A1BG-AS1', 'A1CF', 'A2M', 'A2ML1', 'A4GALT', 'A4GNT', 'AAA1', 'AAAS', 'AACS']\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data saved to ../../output/preprocess/Eczema/gene_data/GSE57225.csv\n", "\n", "Linking clinical and genetic data...\n", "Linked data shape: (62, 19364)\n", "Linked data preview (first 5 rows, 5 columns):\n", " Eczema Age Gender A1BG A1BG-AS1\n", "GSM1377461 NaN 48.0 1.0 12.977107 6.935017\n", "GSM1377462 1.0 48.0 1.0 13.381272 7.078788\n", "GSM1377463 NaN 40.0 1.0 11.371641 7.111287\n", "GSM1377464 1.0 40.0 1.0 13.209966 7.637369\n", "GSM1377465 0.0 65.0 1.0 12.411935 7.016705\n", "\n", "Handling missing values...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data shape after handling missing values: (40, 19364)\n", "\n", "Checking for bias in dataset features...\n", "For the feature 'Eczema', the least common label is '0.0' with 17 occurrences. This represents 42.50% of the dataset.\n", "The distribution of the feature 'Eczema' in this dataset is fine.\n", "\n", "Quartiles for 'Age':\n", " 25%: 34.5\n", " 50% (Median): 46.0\n", " 75%: 56.0\n", "Min: 20.0\n", "Max: 72.0\n", "The distribution of the feature 'Age' in this dataset is fine.\n", "\n", "For the feature 'Gender', the least common label is '1.0' with 13 occurrences. This represents 32.50% of the dataset.\n", "The distribution of the feature 'Gender' in this dataset is fine.\n", "\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data saved to ../../output/preprocess/Eczema/GSE57225.csv\n" ] } ], "source": [ "# 1. Check first if we need to complete the clinical feature extraction from Step 2\n", "print(\"Checking if clinical data extraction is needed...\")\n", "if not os.path.exists(out_clinical_data_file):\n", " print(\"Clinical data file not found. Extracting clinical features from original data...\")\n", " # Get the matrix file path\n", " _, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", " \n", " # Get the clinical data from the matrix file\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", " # Define conversion functions from Step 2\n", " def convert_trait(value: str) -> Optional[int]:\n", " if value is None:\n", " return None\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " if 'eczema' in value.lower():\n", " return 1 # Case\n", " elif 'control' in value.lower() or 'non-involved' in value.lower():\n", " return 0 # Control\n", " else:\n", " return None # Other conditions like psoriasis\n", "\n", " def convert_age(value: str) -> Optional[float]:\n", " if value is None:\n", " return None\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " age_match = re.search(r'(\\d+)', value)\n", " if age_match:\n", " return float(age_match.group(1))\n", " return None\n", "\n", " def convert_gender(value: str) -> Optional[int]:\n", " if value is None:\n", " return None\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " if 'female' in value.lower():\n", " return 0\n", " elif 'male' in value.lower():\n", " return 1\n", " return None\n", " \n", " # Extract clinical features with identified rows from Step 2\n", " trait_row = 1\n", " age_row = 4\n", " gender_row = 3\n", " \n", " clinical_features = geo_select_clinical_features(\n", " 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", " # Save clinical features\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 features extracted and saved to: {out_clinical_data_file}\")\n", "else:\n", " print(f\"Clinical data file already exists at: {out_clinical_data_file}\")\n", " clinical_features = pd.read_csv(out_clinical_data_file, index_col=0)\n", "\n", "# Now proceed with Step 7 as originally planned\n", "# 1. Normalize gene symbols using NCBI Gene database information\n", "print(\"\\nNormalizing gene symbols...\")\n", "try:\n", " # Load the gene data if needed\n", " if 'gene_data' not in locals() or gene_data is None:\n", " gene_data = pd.read_csv(out_gene_data_file, index_col=0)\n", " \n", " # Normalize gene symbols\n", " normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", " print(f\"Gene data shape after normalization: {normalized_gene_data.shape}\")\n", " print(f\"Sample of normalized gene symbols: {normalized_gene_data.index[:10].tolist()}\")\n", " \n", " # Save the normalized gene data\n", " normalized_gene_data.to_csv(out_gene_data_file)\n", " print(f\"Normalized gene data saved to {out_gene_data_file}\")\n", "except Exception as e:\n", " print(f\"Error normalizing gene symbols: {e}\")\n", "\n", "# 2. Link clinical and genetic data\n", "print(\"\\nLinking clinical and genetic data...\")\n", "try:\n", " # 3. Link clinical and genetic data\n", " linked_data = geo_link_clinical_genetic_data(clinical_features, normalized_gene_data)\n", " print(f\"Linked data shape: {linked_data.shape}\")\n", " print(\"Linked data preview (first 5 rows, 5 columns):\")\n", " if linked_data.shape[0] > 0 and linked_data.shape[1] > 5:\n", " print(linked_data.iloc[:5, :5])\n", " else:\n", " print(linked_data)\n", " \n", " # 4. Handle missing values\n", " print(\"\\nHandling 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", " print(\"\\nChecking for bias in dataset features...\")\n", " is_biased, linked_data_clean = judge_and_remove_biased_features(linked_data_clean, trait)\n", " \n", " # 6. Conduct final quality validation\n", " note = \"Dataset contains gene expression data from skin biopsies comparing different skin conditions including eczema (atopic dermatitis and contact eczema) against other conditions like psoriasis and healthy controls.\"\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=note\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.\")\n", " \n", "except Exception as e:\n", " print(f\"Error processing data: {e}\")\n", " # If processing fails, we should still validate the dataset status\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, # We know trait data is available from step 2\n", " is_biased=True, # Set to True to ensure it's not marked usable\n", " df=pd.DataFrame(), # Empty dataframe since processing failed\n", " note=f\"Failed to process data: {e}\"\n", " )\n", " print(\"Dataset validation completed with error status.\")" ] } ], "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 }