{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "da7695aa", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:56:57.586509Z", "iopub.status.busy": "2025-03-25T07:56:57.586323Z", "iopub.status.idle": "2025-03-25T07:56:57.749350Z", "shell.execute_reply": "2025-03-25T07:56:57.749023Z" } }, "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 = \"Melanoma\"\n", "cohort = \"GSE244984\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Melanoma\"\n", "in_cohort_dir = \"../../input/GEO/Melanoma/GSE244984\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Melanoma/GSE244984.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Melanoma/gene_data/GSE244984.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Melanoma/clinical_data/GSE244984.csv\"\n", "json_path = \"../../output/preprocess/Melanoma/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "d8f558c8", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "79b1920b", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:56:57.750731Z", "iopub.status.busy": "2025-03-25T07:56:57.750597Z", "iopub.status.idle": "2025-03-25T07:56:57.765305Z", "shell.execute_reply": "2025-03-25T07:56:57.765012Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Molecular patterns of resistance to immune checkpoint blockade in melanoma\"\n", "!Series_summary\t\"This SuperSeries is composed of the SubSeries listed below.\"\n", "!Series_overall_design\t\"Refer to individual Series\"\n", "Sample Characteristics Dictionary:\n", "{0: ['patient: Pat10', 'patient: Pat13', 'patient: Pat14', 'patient: Pat19', 'patient: Pat21', 'patient: Pat22', 'patient: Pat23', 'patient: Pat26', 'patient: Pat27', 'patient: Pat32', 'patient: Pat39', 'patient: Pat42', 'patient: Pat44', 'patient: Pat45', 'patient: Pat46', 'patient: Pat49', 'patient: Pat5'], 1: ['resistance: CTLA4res', 'resistance: PD1res']}\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": "db1e5a7a", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "302012b1", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:56:57.766330Z", "iopub.status.busy": "2025-03-25T07:56:57.766227Z", "iopub.status.idle": "2025-03-25T07:56:57.770882Z", "shell.execute_reply": "2025-03-25T07:56:57.770607Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Clinical data file not found. Skipping clinical feature extraction.\n" ] } ], "source": [ "import pandas as pd\n", "import os\n", "import json\n", "from typing import Callable, Optional, Dict, Any\n", "\n", "# Let's analyze the dataset based on the given information\n", "\n", "# 1. Gene Expression Data Availability\n", "# Checking for gene expression data\n", "# Since this is a SuperSeries from GEO and there's no clear indication of what type of data it contains,\n", "# we need to be cautious and check further. However, there's no explicit evidence that this is purely miRNA\n", "# or methylation data, so we'll assume it might contain gene expression data.\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# Looking at the sample characteristics dictionary:\n", "# 0: Patient IDs\n", "# 1: Resistance status (CTLA4res, PD1res) - This could be related to melanoma treatment response\n", "\n", "# 2.1 Identify keys for trait, age, gender\n", "trait_row = 1 # Resistance status could be considered as a trait related to melanoma\n", "age_row = None # Age data is not available in the provided sample characteristics\n", "gender_row = None # Gender data is not available in the provided sample characteristics\n", "\n", "# 2.2 Data Type Conversion Functions\n", "def convert_trait(value: str) -> int:\n", " \"\"\"Convert resistance status to binary trait.\n", " CTLA4res: resistant to CTLA4 inhibitors\n", " PD1res: resistant to PD1 inhibitors\n", " Both are related to treatment resistance in melanoma.\n", " \"\"\"\n", " if not value or ':' not in value:\n", " return None\n", " \n", " value = value.split(':', 1)[1].strip().lower()\n", " \n", " # Convert to binary: 1 for PD1 resistance, 0 for CTLA4 resistance\n", " if 'pd1res' in value:\n", " return 1\n", " elif 'ctla4res' in value:\n", " return 0\n", " else:\n", " return None\n", "\n", "def convert_age(value: str) -> float:\n", " \"\"\"This function is a placeholder since age data is not available.\"\"\"\n", " return None\n", "\n", "def convert_gender(value: str) -> int:\n", " \"\"\"This function is a placeholder since gender data is not available.\"\"\"\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Perform initial filtering on usability and save information\n", "is_trait_available = trait_row is not None\n", "validate_and_save_cohort_info(is_final=False, cohort=cohort, info_path=json_path, \n", " is_gene_available=is_gene_available, \n", " is_trait_available=is_trait_available)\n", "\n", "# 4. Clinical Feature Extraction\n", "# If trait data is available, extract clinical features\n", "if trait_row is not None:\n", " try:\n", " # Assuming clinical_data has been loaded in a previous step\n", " clinical_data = pd.read_csv(f\"{in_cohort_dir}/clinical_data.csv\")\n", " \n", " # Extract clinical features using the library function\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(\"Clinical Features Preview:\")\n", " print(preview)\n", " \n", " # Save the clinical data\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " selected_clinical_df.to_csv(out_clinical_data_file, index=False)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n", " except FileNotFoundError:\n", " print(\"Clinical data file not found. Skipping clinical feature extraction.\")\n" ] }, { "cell_type": "markdown", "id": "afadd5f9", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "cd93be2b", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:56:57.771836Z", "iopub.status.busy": "2025-03-25T07:56:57.771734Z", "iopub.status.idle": "2025-03-25T07:56:57.795679Z", "shell.execute_reply": "2025-03-25T07:56:57.795401Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "This appears to be a SuperSeries. Looking at the SOFT file to find potential subseries:\n", "Found potential subseries references:\n", "!Series_relation = SuperSeries of: GSE244982\n", "!Series_relation = SuperSeries of: GSE244983\n", "!Series_relation = SuperSeries of: GSE261347\n", "\n", "Gene data extraction result:\n", "Number of rows: 1825\n", "First 20 gene/probe identifiers:\n", "Index(['A2M', 'ABCB1', 'ABCF1', 'ABL1', 'ACOT12', 'ACSF3', 'ACTA2', 'ACTB',\n", " 'ACTR3B', 'ACVR1B', 'ACVR1C', 'ACVR2A', 'ACY1', 'ADA', 'ADAM12',\n", " 'ADGRE1', 'ADH1A', 'ADH1B', 'ADH1C', 'ADH4'],\n", " dtype='object', name='ID')\n" ] } ], "source": [ "# 1. First get the path to the soft and matrix files\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# 2. Looking more carefully at the background information\n", "# This is a SuperSeries which doesn't contain direct gene expression data\n", "# Need to investigate the soft file to find the subseries\n", "print(\"This appears to be a SuperSeries. Looking at the SOFT file to find potential subseries:\")\n", "\n", "# Open the SOFT file to try to identify subseries\n", "with gzip.open(soft_file, 'rt') as f:\n", " subseries_lines = []\n", " for i, line in enumerate(f):\n", " if 'Series_relation' in line and 'SuperSeries of' in line:\n", " subseries_lines.append(line.strip())\n", " if i > 1000: # Limit search to first 1000 lines\n", " break\n", "\n", "# Display the subseries found\n", "if subseries_lines:\n", " print(\"Found potential subseries references:\")\n", " for line in subseries_lines:\n", " print(line)\n", "else:\n", " print(\"No subseries references found in the first 1000 lines of the SOFT file.\")\n", "\n", "# Despite trying to extract gene data, we expect it might fail because this is a SuperSeries\n", "try:\n", " gene_data = get_genetic_data(matrix_file)\n", " print(\"\\nGene data extraction result:\")\n", " print(\"Number of rows:\", len(gene_data))\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", " print(\"This confirms the dataset is a SuperSeries without direct gene expression data.\")\n" ] }, { "cell_type": "markdown", "id": "43c8e670", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "a5f29c32", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:56:57.796661Z", "iopub.status.busy": "2025-03-25T07:56:57.796562Z", "iopub.status.idle": "2025-03-25T07:56:57.798285Z", "shell.execute_reply": "2025-03-25T07:56:57.798012Z" } }, "outputs": [], "source": [ "# Reviewing the gene identifiers in the gene expression data\n", "# Based on biomedical knowledge, these appear to be standard human gene symbols:\n", "# - A2M (Alpha-2-Macroglobulin)\n", "# - ABCB1 (ATP Binding Cassette Subfamily B Member 1)\n", "# - ABCF1 (ATP Binding Cassette Subfamily F Member 1)\n", "# - ABL1 (ABL Proto-Oncogene 1, Non-Receptor Tyrosine Kinase)\n", "# - ACTA2 (Actin Alpha 2, Smooth Muscle)\n", "# - ACTB (Actin Beta)\n", "# - etc.\n", "\n", "# These are all standard HGNC (HUGO Gene Nomenclature Committee) gene symbols\n", "# No gene mapping is required, as these are already in the desired format\n", "\n", "requires_gene_mapping = False\n" ] }, { "cell_type": "markdown", "id": "214f9dc3", "metadata": {}, "source": [ "### Step 5: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 6, "id": "a97e304d", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:56:57.799207Z", "iopub.status.busy": "2025-03-25T07:56:57.799107Z", "iopub.status.idle": "2025-03-25T07:56:58.267039Z", "shell.execute_reply": "2025-03-25T07:56:58.266670Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Top 10 gene indices before normalization: ['A2M', 'ABCB1', 'ABCF1', 'ABL1', 'ACOT12', 'ACSF3', 'ACTA2', 'ACTB', 'ACTR3B', 'ACVR1B']\n", "Top 10 gene indices after normalization: ['A2M', 'ABCB1', 'ABCF1', 'ABL1', 'ACOT12', 'ACSF3', 'ACTA2', 'ACTB', 'ACTR3B', 'ACVR1B']\n", "Shape of normalized gene data: (1820, 33)\n", "Saved normalized gene data to ../../output/preprocess/Melanoma/gene_data/GSE244984.csv\n", "Saved clinical data to ../../output/preprocess/Melanoma/clinical_data/GSE244984.csv\n", "Shape of linked data: (33, 1821)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Shape of linked data after handling missing values: (33, 1821)\n", "For the feature 'Melanoma', the least common label is '1.0' with 14 occurrences. This represents 42.42% of the dataset.\n", "The distribution of the feature 'Melanoma' in this dataset is fine.\n", "\n", "Saved processed linked data to ../../output/preprocess/Melanoma/GSE244984.csv\n" ] } ], "source": [ "# 1. Normalize gene symbols in the gene expression data\n", "print(f\"Top 10 gene indices before normalization: {gene_data.index[:10].tolist()}\")\n", "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"Top 10 gene indices after normalization: {normalized_gene_data.index[:10].tolist()}\")\n", "print(f\"Shape of normalized gene data: {normalized_gene_data.shape}\")\n", "\n", "# Create directory for gene data file if it doesn't exist\n", "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", "# Save the normalized gene data\n", "normalized_gene_data.to_csv(out_gene_data_file)\n", "print(f\"Saved normalized gene data to {out_gene_data_file}\")\n", "\n", "# 2. Extract clinical features using the clinical data from step 1\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 using the convert_trait function from step 2\n", "selected_clinical_df = geo_select_clinical_features(\n", " clinical_df=clinical_data,\n", " trait=trait,\n", " trait_row=1, # From step 2\n", " convert_trait=convert_trait,\n", " age_row=None,\n", " convert_age=None,\n", " gender_row=None,\n", " convert_gender=None\n", ")\n", "\n", "# Save clinical data\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\"Saved clinical data to {out_clinical_data_file}\")\n", "\n", "# 3. Link clinical and genetic data\n", "linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)\n", "print(f\"Shape of linked data: {linked_data.shape}\")\n", "\n", "# 4. Handle missing values in the linked data\n", "linked_data = handle_missing_values(linked_data, trait)\n", "print(f\"Shape of linked data after handling missing values: {linked_data.shape}\")\n", "\n", "# 5. Determine if the trait and demographic features are biased\n", "is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)\n", "\n", "# 6. Validate the dataset and save cohort information\n", "is_usable = validate_and_save_cohort_info(\n", " is_final=True,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=True,\n", " is_trait_available=True,\n", " is_biased=is_trait_biased,\n", " df=unbiased_linked_data,\n", " note=\"Dataset contains gene expression data from juvenile myositis (JM) and childhood-onset lupus (cSLE) skin biopsies.\"\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", " unbiased_linked_data.to_csv(out_data_file)\n", " print(f\"Saved processed linked data to {out_data_file}\")\n", "else:\n", " print(\"Dataset validation failed. Final 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 }