{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "0d874a86", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:59:15.244952Z", "iopub.status.busy": "2025-03-25T07:59:15.244840Z", "iopub.status.idle": "2025-03-25T07:59:15.407885Z", "shell.execute_reply": "2025-03-25T07:59:15.407546Z" } }, "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 = \"Mesothelioma\"\n", "cohort = \"GSE248514\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Mesothelioma\"\n", "in_cohort_dir = \"../../input/GEO/Mesothelioma/GSE248514\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Mesothelioma/GSE248514.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Mesothelioma/gene_data/GSE248514.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Mesothelioma/clinical_data/GSE248514.csv\"\n", "json_path = \"../../output/preprocess/Mesothelioma/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "4956e0fd", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "94b2f7dd", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:59:15.409374Z", "iopub.status.busy": "2025-03-25T07:59:15.409229Z", "iopub.status.idle": "2025-03-25T07:59:15.433841Z", "shell.execute_reply": "2025-03-25T07:59:15.433552Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Files in the directory:\n", "['GSE248514_family.soft.gz', 'GSE248514_series_matrix.txt.gz']\n", "SOFT file: ../../input/GEO/Mesothelioma/GSE248514/GSE248514_family.soft.gz\n", "Matrix file: ../../input/GEO/Mesothelioma/GSE248514/GSE248514_series_matrix.txt.gz\n", "Background Information:\n", "!Series_title\t\"Coupling of response biomarkers between tumour and peripheral blood in mesothelioma patients undergoing chemoimmunotherapy\"\n", "!Series_summary\t\"Platinum-based chemotherapy in combination with anti-PD-L1 antibodies has shown promising results in mesothelioma. However, the immunological mechanisms underlying its efficacy are not well understood and there are no predictive biomarkers of clinical outcomes to guide treatment decisions. Here, we combine time-course RNA sequencing of peripheral blood mononuclear cells with pre-treatment tumour transcriptome data from the 54-patient cohort in the single arm phase II DREAM study. The identified immunological correlates are predictive of response and provide further evidence for the additive nature of the interaction between platinum-based chemotherapy and PD-L1 antibodies. Our study highlights the complex, but predictive interactions between the tumour and immune cells in peripheral blood during the response to chemoimmunotherapy.\"\n", "!Series_overall_design\t\"Fifty-four participants were recruited to the DREAM clinical trial of durvalumab plus chemotherapy in malignant mesothelioma. Tumour biopsy tissue and matched bloods were collected. To analyse tumour tissue, archival FFPE tissue (blocks or slides) was obtained from participating hospital sites and mRNA was extracted. We retrieved mRNA of sufficient quantity and quality to perform gene expression analysis using the nanoString nCounter platform from 46 of these patients. The nanoString PanCancer IO 360 kit provided gene expression data for 770 immune-oncology related genes. Differential expression of genes were compared between two patient groups based on Progression at 6 months (PFS6) for the purpose of identifying predictive biomarkers. Samples were run as a single replicate, with each nCounter casette containing a manufacturer's QC Standard sample plus up to 11 experimental samples.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['batch: 1', 'batch: 2', 'batch: 3', 'batch: 4', 'batch: 5'], 1: ['lane: 1', 'lane: 2', 'lane: 3', 'lane: 4', 'lane: 5', 'lane: 6', 'lane: 7', 'lane: 8', 'lane: 9', 'lane: 10', 'lane: 11'], 2: ['tissue: mesothelioma'], 3: ['gender: Male', 'gender: Female'], 4: ['histology: Biphasic', 'histology: Epithelioid', 'histology: Desmoplastic', 'histology: Sarcomatoid'], 5: ['progression-free at 6 months: No', 'progression-free at 6 months: Yes']}\n" ] } ], "source": [ "# 1. Check what files are actually in the directory\n", "import os\n", "print(\"Files in the directory:\")\n", "files = os.listdir(in_cohort_dir)\n", "print(files)\n", "\n", "# 2. Find appropriate files with more flexible pattern matching\n", "soft_file = None\n", "matrix_file = None\n", "\n", "for file in files:\n", " file_path = os.path.join(in_cohort_dir, file)\n", " # Look for files that might contain SOFT or matrix data with various possible extensions\n", " if 'soft' in file.lower() or 'family' in file.lower() or file.endswith('.soft.gz'):\n", " soft_file = file_path\n", " if 'matrix' in file.lower() or file.endswith('.txt.gz') or file.endswith('.tsv.gz'):\n", " matrix_file = file_path\n", "\n", "if not soft_file:\n", " print(\"Warning: Could not find a SOFT file. Using the first .gz file as fallback.\")\n", " gz_files = [f for f in files if f.endswith('.gz')]\n", " if gz_files:\n", " soft_file = os.path.join(in_cohort_dir, gz_files[0])\n", "\n", "if not matrix_file:\n", " print(\"Warning: Could not find a matrix file. Using the second .gz file as fallback if available.\")\n", " gz_files = [f for f in files if f.endswith('.gz')]\n", " if len(gz_files) > 1 and soft_file != os.path.join(in_cohort_dir, gz_files[1]):\n", " matrix_file = os.path.join(in_cohort_dir, gz_files[1])\n", " elif len(gz_files) == 1 and not soft_file:\n", " matrix_file = os.path.join(in_cohort_dir, gz_files[0])\n", "\n", "print(f\"SOFT file: {soft_file}\")\n", "print(f\"Matrix file: {matrix_file}\")\n", "\n", "# 3. Read files if found\n", "if soft_file and matrix_file:\n", " # 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", " \n", " try:\n", " background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n", " \n", " # Obtain the sample characteristics dictionary from the clinical dataframe\n", " sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n", " \n", " # 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", " except Exception as e:\n", " print(f\"Error processing files: {e}\")\n", " # Try swapping files if first attempt fails\n", " print(\"Trying to swap SOFT and matrix files...\")\n", " temp = soft_file\n", " soft_file = matrix_file\n", " matrix_file = temp\n", " try:\n", " background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n", " sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n", " print(\"Background Information:\")\n", " print(background_info)\n", " print(\"Sample Characteristics Dictionary:\")\n", " print(sample_characteristics_dict)\n", " except Exception as e:\n", " print(f\"Still error after swapping: {e}\")\n", "else:\n", " print(\"Could not find necessary files for processing.\")\n" ] }, { "cell_type": "markdown", "id": "1683e88e", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "f89ef045", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:59:15.434919Z", "iopub.status.busy": "2025-03-25T07:59:15.434811Z", "iopub.status.idle": "2025-03-25T07:59:15.443876Z", "shell.execute_reply": "2025-03-25T07:59:15.443594Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Preview of selected clinical data:\n", "{'GSM7916142': [0.0, 1.0], 'GSM7916143': [0.0, 1.0], 'GSM7916144': [0.0, 1.0], 'GSM7916145': [0.0, 1.0], 'GSM7916146': [0.0, 0.0], 'GSM7916147': [0.0, 1.0], 'GSM7916148': [1.0, 1.0], 'GSM7916149': [1.0, 1.0], 'GSM7916150': [0.0, 1.0], 'GSM7916151': [1.0, 0.0], 'GSM7916152': [0.0, 1.0], 'GSM7916153': [0.0, 1.0], 'GSM7916154': [1.0, 1.0], 'GSM7916155': [0.0, 1.0], 'GSM7916156': [1.0, 1.0], 'GSM7916157': [0.0, 1.0], 'GSM7916158': [1.0, 1.0], 'GSM7916159': [0.0, 1.0], 'GSM7916160': [1.0, 0.0], 'GSM7916161': [1.0, 1.0], 'GSM7916162': [0.0, 1.0], 'GSM7916163': [1.0, 1.0], 'GSM7916164': [1.0, 1.0], 'GSM7916165': [1.0, 1.0], 'GSM7916166': [1.0, 1.0], 'GSM7916167': [1.0, 0.0], 'GSM7916168': [0.0, 1.0], 'GSM7916169': [0.0, 1.0], 'GSM7916170': [1.0, 1.0], 'GSM7916171': [0.0, 1.0], 'GSM7916172': [0.0, 1.0], 'GSM7916173': [1.0, 1.0], 'GSM7916174': [0.0, 1.0], 'GSM7916175': [0.0, 1.0], 'GSM7916176': [1.0, 0.0], 'GSM7916177': [1.0, 1.0], 'GSM7916178': [1.0, 1.0], 'GSM7916179': [1.0, 1.0], 'GSM7916180': [1.0, 1.0], 'GSM7916181': [0.0, 1.0], 'GSM7916182': [0.0, 1.0], 'GSM7916183': [1.0, 1.0], 'GSM7916184': [1.0, 1.0], 'GSM7916185': [1.0, 1.0], 'GSM7916186': [1.0, 0.0], 'GSM7916187': [0.0, 1.0]}\n", "Clinical data saved to: ../../output/preprocess/Mesothelioma/clinical_data/GSE248514.csv\n" ] } ], "source": [ "# 1. Gene Expression Data Availability\n", "# Based on the Series_summary and Series_overall_design, this dataset contains gene expression data\n", "# from nanoString nCounter platform for 770 immune-oncology related genes\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "\n", "# Trait: Mesothelioma\n", "# From the sample characteristics dictionary, we can use progression-free at 6 months as a trait\n", "# since the study focuses on response biomarkers, and this is a clinically relevant outcome\n", "trait_row = 5 # 'progression-free at 6 months'\n", "\n", "# Age: Not explicitly provided in the sample characteristics\n", "age_row = None # Age data is not available\n", "\n", "# Gender: Available in the sample characteristics\n", "gender_row = 3 # 'gender'\n", "\n", "# 2.2 Data Type Conversion\n", "\n", "# For trait (progression-free at 6 months)\n", "def convert_trait(value):\n", " if value is None:\n", " return None\n", " if isinstance(value, str) and ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " if value.lower() == 'yes':\n", " return 1 # progression-free\n", " elif value.lower() == 'no':\n", " return 0 # not progression-free\n", " return None\n", "\n", "# For gender\n", "def convert_gender(value):\n", " if value is None:\n", " return None\n", " if isinstance(value, str) and ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " if value.lower() == 'female':\n", " return 0\n", " elif value.lower() == 'male':\n", " return 1\n", " return None\n", "\n", "# Convert age function (not used, but defined for completeness)\n", "def convert_age(value):\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Trait data is available (trait_row is not None)\n", "is_trait_available = trait_row is not None\n", "\n", "# Initial filtering validation\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", "# Since trait_row is not None, we need to extract clinical features\n", "if trait_row is not None:\n", " # Use the clinical data that should be available from previous steps\n", " # Typically accessed via a global variable or passed to this function\n", " \n", " # Extract clinical features from clinical_data\n", " selected_clinical_df = geo_select_clinical_features(\n", " clinical_df=clinical_data, # Assuming clinical_data is already available from previous steps\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 data\n", " preview = preview_df(selected_clinical_df)\n", " print(\"Preview of selected clinical data:\")\n", " print(preview)\n", " \n", " # Save the clinical data to CSV\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " selected_clinical_df.to_csv(out_clinical_data_file, index=True)\n", " print(f\"Clinical data saved to: {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "6eeb9255", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "2ee15079", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:59:15.444938Z", "iopub.status.busy": "2025-03-25T07:59:15.444832Z", "iopub.status.idle": "2025-03-25T07:59:15.469489Z", "shell.execute_reply": "2025-03-25T07:59:15.469197Z" } }, "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": "79371f2b", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "827cd5b0", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:59:15.470573Z", "iopub.status.busy": "2025-03-25T07:59:15.470468Z", "iopub.status.idle": "2025-03-25T07:59:15.472260Z", "shell.execute_reply": "2025-03-25T07:59:15.471981Z" } }, "outputs": [], "source": [ "# Gene Identifier Review\n", "\n", "# Observe the gene identifiers provided in the previous step\n", "# The identifiers in the dataset are: 'A2M', 'ABCF1', 'ACVR1C', 'ADAM12', 'ADGRE1', etc.\n", "\n", "# Based on biomedical knowledge, these appear to be human gene symbols (official gene symbols)\n", "# rather than other identifiers like Affymetrix probe IDs, Ensembl IDs, or RefSeq IDs.\n", "# They follow the standard HGNC (HUGO Gene Nomenclature Committee) naming conventions.\n", "\n", "# Therefore, no mapping to gene symbols is required\n", "\n", "requires_gene_mapping = False\n" ] }, { "cell_type": "markdown", "id": "2521a5db", "metadata": {}, "source": [ "### Step 5: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 6, "id": "65ed59f8", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:59:15.473346Z", "iopub.status.busy": "2025-03-25T07:59:15.473243Z", "iopub.status.idle": "2025-03-25T07:59:15.717395Z", "shell.execute_reply": "2025-03-25T07:59:15.717017Z" } }, "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, 46)\n", "Saved normalized gene data to ../../output/preprocess/Mesothelioma/gene_data/GSE248514.csv\n", "Loaded clinical data from ../../output/preprocess/Mesothelioma/clinical_data/GSE248514.csv\n", "Shape of clinical data: (2, 46)\n", "Shape of linked data: (46, 764)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Shape of linked data after handling missing values: (46, 764)\n", "For the feature 'Mesothelioma', the least common label is '0.0' with 22 occurrences. This represents 47.83% of the dataset.\n", "The distribution of the feature 'Mesothelioma' in this dataset is fine.\n", "\n", "For the feature 'Gender', the least common label is '0.0' with 6 occurrences. This represents 13.04% of the dataset.\n", "The distribution of the feature 'Gender' in this dataset is fine.\n", "\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Saved processed linked data to ../../output/preprocess/Mesothelioma/GSE248514.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. Load the clinical data previously preprocessed (from Step 2)\n", "# Use the clinical features previously extracted with the correct trait_row (5)\n", "selected_clinical_df = pd.read_csv(out_clinical_data_file, index_col=0)\n", "print(f\"Loaded clinical data from {out_clinical_data_file}\")\n", "print(f\"Shape of clinical data: {selected_clinical_df.shape}\")\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", "# Check if any samples remain after missing value handling\n", "if linked_data.shape[0] == 0:\n", " print(\"Warning: No samples remain after handling missing values. Check if trait column has valid data.\")\n", " is_usable = False\n", "else:\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 mesothelioma patients undergoing chemoimmunotherapy.\"\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 }