{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "f65f9e81", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:55:07.585268Z", "iopub.status.busy": "2025-03-25T03:55:07.585160Z", "iopub.status.idle": "2025-03-25T03:55:07.742897Z", "shell.execute_reply": "2025-03-25T03:55:07.742459Z" } }, "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 = \"Sarcoma\"\n", "cohort = \"GSE233860\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Sarcoma\"\n", "in_cohort_dir = \"../../input/GEO/Sarcoma/GSE233860\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Sarcoma/GSE233860.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Sarcoma/gene_data/GSE233860.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Sarcoma/clinical_data/GSE233860.csv\"\n", "json_path = \"../../output/preprocess/Sarcoma/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "3f6359d0", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "22258b7a", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:55:07.744219Z", "iopub.status.busy": "2025-03-25T03:55:07.744076Z", "iopub.status.idle": "2025-03-25T03:55:07.755160Z", "shell.execute_reply": "2025-03-25T03:55:07.754769Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Files in the directory:\n", "['GSE233860_family.soft.gz', 'GSE233860_series_matrix.txt.gz']\n", "SOFT file: ../../input/GEO/Sarcoma/GSE233860/GSE233860_family.soft.gz\n", "Matrix file: ../../input/GEO/Sarcoma/GSE233860/GSE233860_series_matrix.txt.gz\n", "Background Information:\n", "!Series_title\t\"Paired tumour biopsy gene expression data from patients with solid tumours, before and after combination treatment.\"\n", "!Series_summary\t\"Gene expression quantification of PanCancer IO genes from paired tumour biopsies from 24 patients with pan-cancer solid tumours, before and after treatment with MTL-CEBPA and pembrolizumab.\"\n", "!Series_overall_design\t\"Normalised, transformed gene counts of nCounter Nanostring PanCancer IO panel (770 genes) of paired tumour biopsies from 24 patients with solid tumours, before treatment (Screening) and 6 weeks after treatment (C2D16) with MTL-CEBPA and pembrolizumab.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['outcome: SD', 'outcome: PD', 'outcome: PR']}\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": "4c378332", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "75f0fb41", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:55:07.756418Z", "iopub.status.busy": "2025-03-25T03:55:07.756312Z", "iopub.status.idle": "2025-03-25T03:55:07.762796Z", "shell.execute_reply": "2025-03-25T03:55:07.762455Z" } }, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Analyze dataset characteristics\n", "\n", "# 1. Gene Expression Data Availability\n", "# Based on the background information, this dataset contains gene expression data\n", "# It mentions \"Gene expression quantification of PanCancer IO genes\" and \"Normalised, transformed gene counts\"\n", "is_gene_available = True \n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "\n", "# For trait (Sarcoma)\n", "# Looking at the sample characteristics, there's no direct mention of sarcoma\n", "# The dataset is about \"pan-cancer solid tumours\" which may include sarcoma, but no specific indication\n", "trait_row = None # No specific indication that this dataset contains sarcoma data\n", "\n", "# For age\n", "# No age information is available in the sample characteristics\n", "age_row = None\n", "\n", "# For gender\n", "# No gender information is available in the sample characteristics\n", "gender_row = None\n", "\n", "# 2.2 Data Type Conversion\n", "# Since we don't have trait, age, or gender data available, we'll define simple functions \n", "# that would handle the conversion if the data were available\n", "\n", "def convert_trait(value):\n", " if value is None:\n", " return None\n", " # If we had trait data, we would extract the value after colon and convert to binary\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " # Return 1 if it's a sarcoma case, 0 otherwise\n", " return 1 if 'sarcoma' in value.lower() else 0\n", "\n", "def convert_age(value):\n", " if value is None:\n", " return None\n", " # If we had age data, we would extract the numeric value\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " try:\n", " return float(value)\n", " except (ValueError, TypeError):\n", " return None\n", "\n", "def convert_gender(value):\n", " if value is None:\n", " return None\n", " # If we had gender data, we would convert to binary\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip().lower()\n", " if 'female' in value or 'f' == value:\n", " return 0\n", " elif 'male' in value or 'm' == value:\n", " return 1\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Determine trait data availability\n", "is_trait_available = trait_row is not None\n", "\n", "# Save the cohort information using the provided function\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 None, we skip this substep\n" ] }, { "cell_type": "markdown", "id": "fd970b8a", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "bb3f22bf", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:55:07.763808Z", "iopub.status.busy": "2025-03-25T03:55:07.763705Z", "iopub.status.idle": "2025-03-25T03:55:07.777750Z", "shell.execute_reply": "2025-03-25T03:55:07.777377Z" } }, "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: 770\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": "2a3aaa28", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "437714fd", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:55:07.778933Z", "iopub.status.busy": "2025-03-25T03:55:07.778830Z", "iopub.status.idle": "2025-03-25T03:55:07.780680Z", "shell.execute_reply": "2025-03-25T03:55:07.780375Z" } }, "outputs": [], "source": [ "# Looking at the gene identifiers in the gene expression data\n", "# Based on biomedical knowledge, these appear to be standard human gene symbols (like A2M, ABCF1, etc.)\n", "# These are recognized official gene symbols, not probe IDs or other identifiers that would need mapping\n", "\n", "requires_gene_mapping = False\n" ] }, { "cell_type": "markdown", "id": "696a2613", "metadata": {}, "source": [ "### Step 5: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 6, "id": "4ece4f73", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:55:07.781867Z", "iopub.status.busy": "2025-03-25T03:55:07.781768Z", "iopub.status.idle": "2025-03-25T03:55:08.006358Z", "shell.execute_reply": "2025-03-25T03:55:08.005868Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Shape of gene data after normalization: (762, 48)\n", "First few gene symbols: ['A2M', 'ABCF1', 'ACVR1C', 'ADAM12', 'ADGRE1']\n", "Sample IDs in gene data: ['GSM7438145', 'GSM7438146', 'GSM7438147', 'GSM7438148', 'GSM7438149']...\n", "Normalized gene data saved to ../../output/preprocess/Sarcoma/gene_data/GSE233860.csv\n", "Based on earlier analysis, this dataset does not contain sarcoma trait information.\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Shape of linked data after handling missing values: (48, 763)" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Quartiles for 'Sarcoma':\n", " 25%: 0.0\n", " 50% (Median): 0.0\n", " 75%: 0.0\n", "Min: 0\n", "Max: 0\n", "The distribution of the feature 'Sarcoma' in this dataset is severely biased.\n", "\n", "Clinical data (placeholder) saved to ../../output/preprocess/Sarcoma/clinical_data/GSE233860.csv\n", "Dataset validation failed. Final linked data not saved.\n" ] } ], "source": [ "# 1. Normalize gene symbols in the gene expression data\n", "gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"Shape of gene data after normalization: {gene_data.shape}\")\n", "print(f\"First few gene symbols: {gene_data.index[:5].tolist()}\")\n", "print(f\"Sample IDs in gene data: {gene_data.columns[:5].tolist()}...\")\n", "\n", "# Save the normalized gene data\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\"Normalized gene data saved to {out_gene_data_file}\")\n", "\n", "# 2. Since we determined in Step 2 that trait_row is None (no sarcoma data available),\n", "# we cannot properly link clinical and genetic data for our target trait\n", "print(\"Based on earlier analysis, this dataset does not contain sarcoma trait information.\")\n", "\n", "# Create a minimal dataframe with the trait column (all zeros as placeholder)\n", "# This allows our functions to run properly even though the data is not usable for analysis\n", "linked_data = gene_data.T.copy()\n", "linked_data[trait] = 0 # Add placeholder trait column\n", "\n", "# 3. Handle missing values in the linked data\n", "# Even though we know the data isn't usable, we run this to satisfy function requirements\n", "linked_data_cleaned = handle_missing_values(linked_data, trait)\n", "print(f\"Shape of linked data after handling missing values: {linked_data_cleaned.shape}\")\n", "\n", "# 4. Check if the trait and demographic features are biased\n", "# Using a placeholder dataframe with trait column so the function runs properly\n", "is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data_cleaned, trait)\n", "\n", "# Create a minimal clinical dataframe to save\n", "clinical_df = pd.DataFrame(index=linked_data.index)\n", "clinical_df[trait] = 0 # Add placeholder trait column\n", "os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", "clinical_df.to_csv(out_clinical_data_file)\n", "print(f\"Clinical data (placeholder) saved to {out_clinical_data_file}\")\n", "\n", "# 5. Validate the dataset and save cohort information\n", "note = \"Dataset contains gene expression data from pan-cancer solid tumors before and after treatment, but does not contain specific sarcoma trait information. Placeholder trait values were added for technical validation only.\"\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=False, # We determined in step 2 that trait data is not available\n", " is_biased=False, # Providing a value as required, though it's not meaningful since trait data is absent\n", " df=unbiased_linked_data,\n", " note=note\n", ")\n", "\n", "# We already know the data is not usable for our purposes, but we'll check the flag anyway\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 }