{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "d46c8b52", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:56:55.483210Z", "iopub.status.busy": "2025-03-25T07:56:55.483025Z", "iopub.status.idle": "2025-03-25T07:56:55.643520Z", "shell.execute_reply": "2025-03-25T07:56:55.643191Z" } }, "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 = \"GSE202806\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Melanoma\"\n", "in_cohort_dir = \"../../input/GEO/Melanoma/GSE202806\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Melanoma/GSE202806.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Melanoma/gene_data/GSE202806.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Melanoma/clinical_data/GSE202806.csv\"\n", "json_path = \"../../output/preprocess/Melanoma/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "75e50552", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "e0b9a49b", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:56:55.644902Z", "iopub.status.busy": "2025-03-25T07:56:55.644769Z", "iopub.status.idle": "2025-03-25T07:56:55.666562Z", "shell.execute_reply": "2025-03-25T07:56:55.666279Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Transcriptomic analyses of NF1-mutant melanoma\"\n", "!Series_summary\t\"RNA analysis of 770 genes (Pan Cancer IO 360) related to the tumor microenvironment on NF1-MUT and matched NF1-WT samples for reference.\"\n", "!Series_overall_design\t\"Multiplex gene expression analysis covers 770 genes from 24 different immune cell types and 48 gene-derived signatures measuring biological variables crucial to the tumor-immune interaction including cell proliferation, angiogenesis and immune inhibitory mechanisms, among others.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['tissue: Melanoma'], 1: ['nf1 status: WT', 'nf1 status: MUT']}\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": "42243b15", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "68b7dd2f", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:56:55.667532Z", "iopub.status.busy": "2025-03-25T07:56:55.667431Z", "iopub.status.idle": "2025-03-25T07:56:55.674721Z", "shell.execute_reply": "2025-03-25T07:56:55.674455Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Clinical Features Preview: {'GSM6133552': [0.0], 'GSM6133553': [0.0], 'GSM6133554': [0.0], 'GSM6133555': [0.0], 'GSM6133556': [0.0], 'GSM6133557': [1.0], 'GSM6133558': [1.0], 'GSM6133559': [1.0], 'GSM6133560': [1.0], 'GSM6133561': [1.0], 'GSM6133562': [0.0], 'GSM6133563': [1.0], 'GSM6133564': [1.0], 'GSM6133565': [1.0], 'GSM6133566': [1.0], 'GSM6133567': [1.0], 'GSM6133568': [1.0], 'GSM6133569': [1.0], 'GSM6133570': [1.0], 'GSM6133571': [1.0], 'GSM6133572': [0.0], 'GSM6133573': [0.0], 'GSM6133574': [0.0], 'GSM6133575': [0.0], 'GSM6133576': [0.0], 'GSM6133577': [0.0], 'GSM6133578': [0.0], 'GSM6133579': [0.0], 'GSM6133580': [0.0], 'GSM6133581': [1.0], 'GSM6133582': [0.0], 'GSM6133583': [0.0], 'GSM6133584': [1.0], 'GSM6133585': [1.0], 'GSM6133586': [0.0], 'GSM6133587': [0.0], 'GSM6133588': [1.0], 'GSM6133589': [0.0], 'GSM6133590': [0.0], 'GSM6133591': [0.0], 'GSM6133592': [1.0], 'GSM6133593': [0.0], 'GSM6133594': [0.0], 'GSM6133595': [1.0], 'GSM6133596': [0.0], 'GSM6133597': [1.0], 'GSM6133598': [1.0], 'GSM6133599': [1.0], 'GSM6133600': [0.0], 'GSM6133601': [0.0], 'GSM6133602': [0.0], 'GSM6133603': [1.0]}\n", "Clinical data saved to ../../output/preprocess/Melanoma/clinical_data/GSE202806.csv\n" ] } ], "source": [ "# 1. Gene Expression Data Availability\n", "# From the background information, we see this dataset contains gene expression data for 770 genes\n", "# related to tumor microenvironment, so it's suitable for our analysis.\n", "is_gene_available = True\n", "\n", "# 2.1 Data Availability\n", "# Examining the sample characteristics dictionary:\n", "# - Key 0 shows 'tissue: Melanoma' which is constant for all samples (not useful for trait)\n", "# - Key 1 shows 'nf1 status: WT' and 'nf1 status: MUT' which can be used as our trait variable\n", "\n", "# For Melanoma trait, we'll use NF1 mutation status as the binary trait\n", "trait_row = 1 # nf1 status\n", "\n", "# Age and gender information are not available in the sample characteristics\n", "age_row = None\n", "gender_row = None\n", "\n", "# 2.2 Data Type Conversion Functions\n", "def convert_trait(value):\n", " \"\"\"Convert NF1 mutation status to binary values.\"\"\"\n", " if not isinstance(value, str):\n", " return None\n", " \n", " # Extract the value after colon if present\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Convert NF1 status to binary\n", " if value.upper() == 'MUT':\n", " return 1 # Mutated\n", " elif value.upper() == 'WT':\n", " return 0 # Wild type\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age values to numeric format.\"\"\"\n", " # Not applicable for this dataset\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender values to binary format.\"\"\"\n", " # Not applicable for this dataset\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", "\n", "# Validate and save cohort info\n", "validate_and_save_cohort_info(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", "# 4. Clinical Feature Extraction\n", "# If trait data is available, extract clinical features\n", "if trait_row is not None:\n", " # Extract clinical features\n", " clinical_features_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(clinical_features_df)\n", " print(\"Clinical Features Preview:\", preview)\n", " \n", " # Save the clinical data\n", " clinical_features_df.to_csv(out_clinical_data_file)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "96593bea", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "0be1aede", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:56:55.675647Z", "iopub.status.busy": "2025-03-25T07:56:55.675546Z", "iopub.status.idle": "2025-03-25T07:56:55.692214Z", "shell.execute_reply": "2025-03-25T07:56:55.691934Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "This appears to be a SuperSeries. Looking at the SOFT file to find potential subseries:\n", "No subseries references found in the first 1000 lines of the SOFT file.\n", "\n", "Gene data extraction result:\n", "Number of rows: 784\n", "First 20 gene/probe identifiers:\n", "Index(['A2M', 'ABCF1', 'ACVR1C', 'ADAM12', 'ADGRE1', 'ADM', 'ADORA2A', 'AKT1',\n", " 'ALDOA', 'ALDOC', 'ANGPT1', 'ANGPT2', 'ANGPTL4', 'ANLN', 'APC', 'APH1B',\n", " 'API5', 'APLNR', 'APOE', 'APOL6'],\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": "42e471aa", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "3200937f", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:56:55.693129Z", "iopub.status.busy": "2025-03-25T07:56:55.693029Z", "iopub.status.idle": "2025-03-25T07:56:55.694663Z", "shell.execute_reply": "2025-03-25T07:56:55.694403Z" } }, "outputs": [], "source": [ "# The gene identifiers in the data are human gene symbols (A2M, ABCF1, ACVR1C, etc.)\n", "# These are standard HGNC gene symbols that don't require mapping to other identifiers\n", "\n", "requires_gene_mapping = False\n" ] }, { "cell_type": "markdown", "id": "6545b7e2", "metadata": {}, "source": [ "### Step 5: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 6, "id": "c8d1524d", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:56:55.695609Z", "iopub.status.busy": "2025-03-25T07:56:55.695513Z", "iopub.status.idle": "2025-03-25T07:56:55.948201Z", "shell.execute_reply": "2025-03-25T07:56:55.947824Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Top 10 gene indices before normalization: ['A2M', 'ABCF1', 'ACVR1C', 'ADAM12', 'ADGRE1', 'ADM', 'ADORA2A', 'AKT1', 'ALDOA', 'ALDOC']\n", "Top 10 gene indices after normalization: ['A2M', 'ABCF1', 'ACVR1C', 'ADAM12', 'ADGRE1', 'ADM', 'ADORA2A', 'AKT1', 'ALDOA', 'ALDOC']\n", "Shape of normalized gene data: (762, 52)\n", "Saved normalized gene data to ../../output/preprocess/Melanoma/gene_data/GSE202806.csv\n", "Saved clinical data to ../../output/preprocess/Melanoma/clinical_data/GSE202806.csv\n", "Shape of linked data: (52, 763)\n", "Shape of linked data after handling missing values: (52, 763)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "For the feature 'Melanoma', the least common label is '1.0' with 24 occurrences. This represents 46.15% of the dataset.\n", "The distribution of the feature 'Melanoma' in this dataset is fine.\n", "\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Saved processed linked data to ../../output/preprocess/Melanoma/GSE202806.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 }