{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "51b3a181", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:56:58.923346Z", "iopub.status.busy": "2025-03-25T07:56:58.923242Z", "iopub.status.idle": "2025-03-25T07:56:59.081829Z", "shell.execute_reply": "2025-03-25T07:56:59.081484Z" } }, "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 = \"GSE261347\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Melanoma\"\n", "in_cohort_dir = \"../../input/GEO/Melanoma/GSE261347\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Melanoma/GSE261347.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Melanoma/gene_data/GSE261347.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Melanoma/clinical_data/GSE261347.csv\"\n", "json_path = \"../../output/preprocess/Melanoma/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "f4ac0a2a", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "72989cc2", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:56:59.083257Z", "iopub.status.busy": "2025-03-25T07:56:59.083118Z", "iopub.status.idle": "2025-03-25T07:56:59.092385Z", "shell.execute_reply": "2025-03-25T07:56:59.092100Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Molecular patterns of resistance to immune checkpoint blockade in melanoma [NanoString GeoMx]\"\n", "!Series_summary\t\"Tumor cell-containing Regions of Interest from 17 patients with melanoma after progression to Immune Checkpoint Blockade were profiled at the transcriptomic level.\"\n", "!Series_overall_design\t\"Spatial digital profiling of 33 Regions of Interest from 17 patients with melanoma, using NanoString GeoMx platform for 1825 gene identifiers from the Cancer Transcriptome Atlas.\"\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": "d74b6f74", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "133e9eee", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:56:59.093420Z", "iopub.status.busy": "2025-03-25T07:56:59.093315Z", "iopub.status.idle": "2025-03-25T07:56:59.100021Z", "shell.execute_reply": "2025-03-25T07:56:59.099744Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Clinical Data Preview:\n", "{'GSM8140965': [0.0], 'GSM8140966': [0.0], 'GSM8140967': [0.0], 'GSM8140968': [0.0], 'GSM8140969': [0.0], 'GSM8140970': [0.0], 'GSM8140971': [0.0], 'GSM8140972': [0.0], 'GSM8140973': [0.0], 'GSM8140974': [0.0], 'GSM8140975': [0.0], 'GSM8140976': [0.0], 'GSM8140977': [0.0], 'GSM8140978': [0.0], 'GSM8140979': [0.0], 'GSM8140980': [0.0], 'GSM8140981': [0.0], 'GSM8140982': [1.0], 'GSM8140983': [1.0], 'GSM8140984': [1.0], 'GSM8140985': [1.0], 'GSM8140986': [1.0], 'GSM8140987': [1.0], 'GSM8140988': [1.0], 'GSM8140989': [1.0], 'GSM8140990': [1.0], 'GSM8140991': [1.0], 'GSM8140992': [1.0], 'GSM8140993': [1.0], 'GSM8140994': [1.0], 'GSM8140995': [1.0], 'GSM8140996': [0.0], 'GSM8140997': [0.0]}\n", "Clinical data saved to ../../output/preprocess/Melanoma/clinical_data/GSE261347.csv\n" ] } ], "source": [ "# Analyzing dataset and extracting clinical features\n", "\n", "# 1. Determine gene expression data availability\n", "# Based on the Series title and summary, this appears to be a gene expression dataset\n", "# \"transcriptomic level\" and \"1825 gene identifiers\" indicate gene expression data\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "# For trait (melanoma): The disease is melanoma for all samples (mentioned in title)\n", "# but we can use \"resistance\" as the trait of interest (in row 1)\n", "trait_row = 1\n", "\n", "# For age: Not provided in the sample characteristics\n", "age_row = None\n", "\n", "# For gender: Not provided in the sample characteristics\n", "gender_row = None\n", "\n", "# 2.2 Data Type Conversion Functions\n", "def convert_trait(value):\n", " \"\"\"Convert resistance status to binary (0/1).\"\"\"\n", " if 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 resistance status to binary\n", " if 'CTLA4res' in value:\n", " return 0 # CTLA4 resistance\n", " elif 'PD1res' in value:\n", " return 1 # PD1 resistance\n", " else:\n", " return None\n", "\n", "# Age conversion function (not used but defined for completeness)\n", "def convert_age(value):\n", " return None\n", "\n", "# Gender conversion function (not used but defined for completeness)\n", "def convert_gender(value):\n", " return None\n", "\n", "# 3. Save metadata about dataset usability\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", "# 4. Clinical Feature Extraction\n", "if trait_row is not None:\n", " # Extract clinical features\n", " clinical_df = geo_select_clinical_features(\n", " clinical_df=clinical_data,\n", " trait=\"Resistance\", # Using \"Resistance\" as the trait name\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 data\n", " preview = preview_df(clinical_df)\n", " print(\"Clinical Data Preview:\")\n", " print(preview)\n", " \n", " # Save the clinical data\n", " clinical_df.to_csv(out_clinical_data_file)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n", "else:\n", " print(\"No trait data available. Skipping clinical feature extraction.\")\n" ] }, { "cell_type": "markdown", "id": "e9754df3", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "1d637b47", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:56:59.101017Z", "iopub.status.busy": "2025-03-25T07:56:59.100906Z", "iopub.status.idle": "2025-03-25T07:56:59.125190Z", "shell.execute_reply": "2025-03-25T07:56:59.124907Z" } }, "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: 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": "522c71c7", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "3e231c37", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:56:59.126190Z", "iopub.status.busy": "2025-03-25T07:56:59.126086Z", "iopub.status.idle": "2025-03-25T07:56:59.127741Z", "shell.execute_reply": "2025-03-25T07:56:59.127475Z" } }, "outputs": [], "source": [ "# Based on the gene identifiers provided, they appear to be standard human gene symbols.\n", "# The identifiers like A2M, ABCB1, ABCF1, ABL1, etc. are recognized official gene symbols \n", "# for human genes rather than probe IDs or other identifiers that would need mapping.\n", "\n", "requires_gene_mapping = False\n" ] }, { "cell_type": "markdown", "id": "95251ebc", "metadata": {}, "source": [ "### Step 5: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 6, "id": "386d7b13", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:56:59.128716Z", "iopub.status.busy": "2025-03-25T07:56:59.128616Z", "iopub.status.idle": "2025-03-25T07:56:59.592669Z", "shell.execute_reply": "2025-03-25T07:56:59.592265Z" } }, "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/GSE261347.csv\n", "Saved clinical data to ../../output/preprocess/Melanoma/clinical_data/GSE261347.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/GSE261347.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 }