{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "8dfc09c4", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:57:44.155016Z", "iopub.status.busy": "2025-03-25T07:57:44.154827Z", "iopub.status.idle": "2025-03-25T07:57:44.323070Z", "shell.execute_reply": "2025-03-25T07:57:44.322714Z" } }, "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 = \"GSE117668\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Mesothelioma\"\n", "in_cohort_dir = \"../../input/GEO/Mesothelioma/GSE117668\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Mesothelioma/GSE117668.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Mesothelioma/gene_data/GSE117668.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Mesothelioma/clinical_data/GSE117668.csv\"\n", "json_path = \"../../output/preprocess/Mesothelioma/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "9cb90f6f", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "fa74ff07", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:57:44.324504Z", "iopub.status.busy": "2025-03-25T07:57:44.324363Z", "iopub.status.idle": "2025-03-25T07:57:44.451121Z", "shell.execute_reply": "2025-03-25T07:57:44.450763Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Files in the directory:\n", "['GSE117668_family.soft.gz', 'GSE117668_series_matrix.txt.gz']\n", "SOFT file: ../../input/GEO/Mesothelioma/GSE117668/GSE117668_family.soft.gz\n", "Matrix file: ../../input/GEO/Mesothelioma/GSE117668/GSE117668_series_matrix.txt.gz\n", "Background Information:\n", "!Series_title\t\"Expression data from in vitro healthy cells and malignant pleural mesothelioma cell lines infected by oncolytic attenuated measles virus or treated by exogenous type I interferon\"\n", "!Series_summary\t\"We used microarrays to analyse antiviral response by mesothelioma cells sensitive or resistant to the oncolytic activity of measles virus\"\n", "!Series_overall_design\t\"4 healthy cells and 12 malignant pleural mesothelioma cell lines were infected with measles virus (MV, MOI 1) or not infected (NI = basal expression) or were treated with type I interferon (IFN : IFN-alpha2 + IFN-Beta, 1000UI/mL) during 48 hours. Cells were lysed and RNA was extracted of each sample. This experiment was performed 3 times. RNA was quantified after purification and same quantity of RNA of the 3 experiments was pooled in the same tube for each sample. Then, RNA was analyzed with microarrays.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['cell type: lung epithelial cells', 'cell type: fibroblasts', 'cell type: endothelial cells', 'cell type: peritoneal mesothelial cells', 'cell type: MPM cell line'], 1: ['diagnosis: healthy', 'diagnosis: malignant pleural mesothelioma\\xa0']}\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": "6803363d", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "97fe36ae", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:57:44.452359Z", "iopub.status.busy": "2025-03-25T07:57:44.452244Z", "iopub.status.idle": "2025-03-25T07:57:44.462468Z", "shell.execute_reply": "2025-03-25T07:57:44.462171Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Preview of selected clinical data:\n", "{'!Sample_characteristics_ch1\\t\"cell type: lung epithelial cells\"\\t\"cell type: lung epithelial cells\"\\t\"cell type: lung epithelial cells\"\\t\"cell type: fibroblasts\"\\t\"cell type: fibroblasts\"\\t\"cell type: fibroblasts\"\\t\"cell type: endothelial cells\"\\t\"cell type: endothelial cells\"\\t\"cell type: endothelial cells\"\\t\"cell type: peritoneal mesothelial cells\"\\t\"cell type: peritoneal mesothelial cells\"\\t\"cell type: peritoneal mesothelial cells\"\\t\"cell type: MPM cell line\"\\t\"cell type: MPM cell line\"\\t\"cell type: MPM cell line\"\\t\"cell type: MPM cell line\"\\t\"cell type: MPM cell line\"\\t\"cell type: MPM cell line\"\\t\"cell type: MPM cell line\"\\t\"cell type: MPM cell line\"\\t\"cell type: MPM cell line\"\\t\"cell type: MPM cell line\"\\t\"cell type: MPM cell line\"\\t\"cell type: MPM cell line\"\\t\"cell type: MPM cell line\"\\t\"cell type: MPM cell line\"\\t\"cell type: MPM cell line\"\\t\"cell type: MPM cell line\"\\t\"cell type: MPM cell line\"\\t\"cell type: MPM cell line\"\\t\"cell type: MPM cell line\"\\t\"cell type: MPM cell line\"\\t\"cell type: MPM cell line\"\\t\"cell type: MPM cell line\"\\t\"cell type: MPM cell line\"\\t\"cell type: MPM cell line\"\\t\"cell type: MPM cell line\"\\t\"cell type: MPM cell line\"\\t\"cell type: MPM cell line\"\\t\"cell type: MPM cell line\"\\t\"cell type: MPM cell line\"\\t\"cell type: MPM cell line\"\\t\"cell type: MPM cell line\"\\t\"cell type: MPM cell line\"\\t\"cell type: MPM cell line\"\\t\"cell type: MPM cell line\"\\t\"cell type: MPM cell line\"\\t\"cell type: MPM cell line\"': [nan], '!Sample_characteristics_ch1\\t\"diagnosis: healthy\"\\t\"diagnosis: healthy\"\\t\"diagnosis: healthy\"\\t\"diagnosis: healthy\"\\t\"diagnosis: healthy\"\\t\"diagnosis: healthy\"\\t\"diagnosis: healthy\"\\t\"diagnosis: healthy\"\\t\"diagnosis: healthy\"\\t\"diagnosis: healthy\"\\t\"diagnosis: healthy\"\\t\"diagnosis: healthy\"\\t\"diagnosis: malignant pleural mesothelioma\\xa0\"\\t\"diagnosis: malignant pleural mesothelioma\\xa0\"\\t\"diagnosis: malignant pleural mesothelioma\\xa0\"\\t\"diagnosis: malignant pleural mesothelioma\\xa0\"\\t\"diagnosis: malignant pleural mesothelioma\\xa0\"\\t\"diagnosis: malignant pleural mesothelioma\\xa0\"\\t\"diagnosis: malignant pleural mesothelioma\\xa0\"\\t\"diagnosis: malignant pleural mesothelioma\\xa0\"\\t\"diagnosis: malignant pleural mesothelioma\\xa0\"\\t\"diagnosis: malignant pleural mesothelioma\\xa0\"\\t\"diagnosis: malignant pleural mesothelioma\\xa0\"\\t\"diagnosis: malignant pleural mesothelioma\\xa0\"\\t\"diagnosis: malignant pleural mesothelioma\\xa0\"\\t\"diagnosis: malignant pleural mesothelioma\\xa0\"\\t\"diagnosis: malignant pleural mesothelioma\\xa0\"\\t\"diagnosis: malignant pleural mesothelioma\\xa0\"\\t\"diagnosis: malignant pleural mesothelioma\\xa0\"\\t\"diagnosis: malignant pleural mesothelioma\\xa0\"\\t\"diagnosis: malignant pleural mesothelioma\\xa0\"\\t\"diagnosis: malignant pleural mesothelioma\\xa0\"\\t\"diagnosis: malignant pleural mesothelioma\\xa0\"\\t\"diagnosis: malignant pleural mesothelioma\\xa0\"\\t\"diagnosis: malignant pleural mesothelioma\\xa0\"\\t\"diagnosis: malignant pleural mesothelioma\\xa0\"\\t\"diagnosis: malignant pleural mesothelioma\\xa0\"\\t\"diagnosis: malignant pleural mesothelioma\\xa0\"\\t\"diagnosis: malignant pleural mesothelioma\\xa0\"\\t\"diagnosis: malignant pleural mesothelioma\\xa0\"\\t\"diagnosis: malignant pleural mesothelioma\\xa0\"\\t\"diagnosis: malignant pleural mesothelioma\\xa0\"\\t\"diagnosis: malignant pleural mesothelioma\\xa0\"\\t\"diagnosis: malignant pleural mesothelioma\\xa0\"\\t\"diagnosis: malignant pleural mesothelioma\\xa0\"\\t\"diagnosis: malignant pleural mesothelioma\\xa0\"\\t\"diagnosis: malignant pleural mesothelioma\\xa0\"\\t\"diagnosis: malignant pleural mesothelioma\\xa0\"': [0.0]}\n", "Clinical data saved to ../../output/preprocess/Mesothelioma/clinical_data/GSE117668.csv\n" ] } ], "source": [ "import pandas as pd\n", "import os\n", "import json\n", "from typing import Optional, Callable, Dict, Any, List\n", "import re\n", "\n", "# 1. Gene Expression Data Availability\n", "# Based on the background information, this dataset contains microarray expression data from cells\n", "# This suggests gene expression data is available\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "# Trait (Mesothelioma) can be inferred from diagnosis in row 1\n", "trait_row = 1\n", "\n", "# No age information is available in the sample characteristics\n", "age_row = None\n", "\n", "# No gender information is available in the sample characteristics\n", "gender_row = None\n", "\n", "# 2.2 Data Type Conversion Functions\n", "def convert_trait(value: str) -> int:\n", " \"\"\"Convert diagnosis information to binary trait value (0 for healthy, 1 for mesothelioma)\"\"\"\n", " if not value or ':' not in value:\n", " return None\n", " \n", " # Extract the diagnosis value after the colon\n", " diagnosis = value.split(':', 1)[1].strip().lower()\n", " \n", " # Convert to binary\n", " if 'healthy' in diagnosis:\n", " return 0\n", " elif 'malignant pleural mesothelioma' in diagnosis:\n", " return 1\n", " else:\n", " return None\n", "\n", "def convert_age(value: str) -> Optional[float]:\n", " \"\"\"Placeholder function for age conversion (not used in this dataset)\"\"\"\n", " return None\n", "\n", "def convert_gender(value: str) -> Optional[int]:\n", " \"\"\"Placeholder function for gender conversion (not used in this dataset)\"\"\"\n", " return None\n", "\n", "# Helper function to extract sample characteristics from GEO series matrix file\n", "def get_feature_data(clinical_df, row_index, feature_name, converter):\n", " \"\"\"Extract feature data from a row in clinical DataFrame and convert it.\"\"\"\n", " feature_values = clinical_df.iloc[row_index, :].tolist()\n", " converted_values = [converter(val) for val in feature_values]\n", " return pd.DataFrame({feature_name: converted_values}, index=clinical_df.columns)\n", "\n", "# 3. Save Metadata - Initial Filtering\n", "# Determine if trait data is available based on whether trait_row is None\n", "is_trait_available = trait_row is not None\n", "\n", "# Save initial validation information\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 (only if trait_row is not None)\n", "if trait_row is not None:\n", " # Process the GEO series matrix file to extract clinical data\n", " matrix_file_path = os.path.join(in_cohort_dir, \"GSE117668_series_matrix.txt.gz\")\n", " \n", " # Read lines from the file until we find the sample characteristics\n", " sample_char_lines = []\n", " with pd.io.common.get_handle(matrix_file_path, 'r', compression='gzip') as handle:\n", " file = handle.handle\n", " line = file.readline()\n", " while line:\n", " if line.startswith(\"!Sample_characteristics_ch\"):\n", " sample_char_lines.append(line.strip())\n", " elif line.startswith(\"!Sample_geo_accession\"):\n", " # Get the sample IDs\n", " sample_ids = line.strip().split('\\t')[1:]\n", " elif line.startswith(\"!series_matrix_table_begin\"):\n", " # We've reached the data section, stop parsing headers\n", " break\n", " line = file.readline()\n", " \n", " # Create a DataFrame for sample characteristics\n", " clinical_data = pd.DataFrame(index=sample_char_lines, columns=sample_ids)\n", " \n", " # Fill the DataFrame with values\n", " for i, line in enumerate(sample_char_lines):\n", " values = line.split('\\t')[1:] # Skip the first element (header)\n", " if len(values) == len(sample_ids):\n", " clinical_data.iloc[i] = values\n", " \n", " # Transpose to have samples as rows and characteristics as columns\n", " clinical_data = clinical_data.T\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 selected clinical data\n", " print(\"Preview of selected clinical data:\")\n", " print(preview_df(selected_clinical_df))\n", " \n", " # Create the output directory if it doesn't exist\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " \n", " # Save the clinical data to CSV\n", " selected_clinical_df.to_csv(out_clinical_data_file, index=False)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "983aeab9", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "4aaaf2ba", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:57:44.463623Z", "iopub.status.busy": "2025-03-25T07:57:44.463514Z", "iopub.status.idle": "2025-03-25T07:57:44.643630Z", "shell.execute_reply": "2025-03-25T07:57:44.643239Z" } }, "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" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene data extraction result:\n", "Number of rows: 29536\n", "First 20 gene/probe identifiers:\n", "Index(['100009613_at', '100009676_at', '10000_at', '10001_at', '10002_at',\n", " '100033413_at', '100033422_at', '100033423_at', '100033424_at',\n", " '100033425_at', '100033426_at', '100033427_at', '100033428_at',\n", " '100033430_at', '100033431_at', '100033432_at', '100033434_at',\n", " '100033435_at', '100033436_at', '100033437_at'],\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": "d29ffa25", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "850790fb", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:57:44.644886Z", "iopub.status.busy": "2025-03-25T07:57:44.644771Z", "iopub.status.idle": "2025-03-25T07:57:44.646671Z", "shell.execute_reply": "2025-03-25T07:57:44.646387Z" } }, "outputs": [], "source": [ "# Examining the gene identifiers pattern\n", "# The identifiers follow a pattern like '100009613_at', '100009676_at', '10000_at'\n", "# This format with \"_at\" suffix is typical of Affymetrix microarray probe IDs\n", "# These are not standard human gene symbols and will need to be mapped to proper gene symbols\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "7fa35d3b", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "4c131a23", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:57:44.647695Z", "iopub.status.busy": "2025-03-25T07:57:44.647591Z", "iopub.status.idle": "2025-03-25T07:57:46.217368Z", "shell.execute_reply": "2025-03-25T07:57:46.216967Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene annotation preview:\n", "{'ID': ['100009613_at', '100009676_at', '10000_at', '10001_at', '10002_at'], 'SPOT_ID': ['100009613', '100009676', '10000', '10001', '10002'], 'Description': ['ANO1 antisense RNA 2 (head to head)', 'ZBTB11 antisense RNA 1', 'AKT serine/threonine kinase 3', 'mediator complex subunit 6', 'nuclear receptor subfamily 2 group E member 3']}\n" ] } ], "source": [ "# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n", "gene_annotation = get_gene_annotation(soft_file)\n", "\n", "# 2. Use the 'preview_df' function from the library to preview the data and print out the results.\n", "print(\"Gene annotation preview:\")\n", "print(preview_df(gene_annotation))\n" ] }, { "cell_type": "markdown", "id": "d72cb0c9", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "078ae7fa", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:57:46.218741Z", "iopub.status.busy": "2025-03-25T07:57:46.218614Z", "iopub.status.idle": "2025-03-25T07:57:46.456580Z", "shell.execute_reply": "2025-03-25T07:57:46.456210Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Sample descriptions to analyze gene symbol format:\n", "0 ANO1 antisense RNA 2 (head to head)\n", "1 ZBTB11 antisense RNA 1\n", "2 AKT serine/threonine kinase 3\n", "3 mediator complex subunit 6\n", "4 nuclear receptor subfamily 2 group E member 3\n", "5 small nucleolar RNA, C/D box 116-1\n", "6 small nucleolar RNA, C/D box 116-10\n", "7 small nucleolar RNA, C/D box 116-11\n", "8 small nucleolar RNA, C/D box 116-12\n", "9 small nucleolar RNA, C/D box 116-13\n", "Name: Description, dtype: object\n", "\n", "Preview of gene mapping data:\n", "{'ID': ['100009613_at', '100009676_at', '10000_at', '10001_at', '10002_at'], 'Gene': ['ANO1 antisense RNA 2 (head to head)', 'ZBTB11 antisense RNA 1', 'AKT serine/threonine kinase 3', 'mediator complex subunit 6', 'nuclear receptor subfamily 2 group E member 3']}\n", "\n", "Preview of gene-level expression data:\n", "Shape: (3151, 48)\n", "Number of genes: 3151\n", "First 5 gene symbols: ['A-', 'A-52', 'A0', 'A1', 'A1-']\n", "First 5 samples: ['GSM3305861', 'GSM3305862', 'GSM3305863', 'GSM3305864', 'GSM3305865']\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene expression data saved to ../../output/preprocess/Mesothelioma/gene_data/GSE117668.csv\n" ] } ], "source": [ "# 1. Determine which columns to use for mapping\n", "# From the gene annotation preview, we see:\n", "# - 'ID' contains identifiers like '100009613_at' which match the gene expression data identifiers\n", "# - 'Description' contains what appears to be gene descriptions which likely include gene symbols\n", "\n", "# First, let's better understand the structure of the Description column\n", "print(\"Sample descriptions to analyze gene symbol format:\")\n", "print(gene_annotation['Description'].head(10))\n", "\n", "# Map gene IDs to gene symbols\n", "# Use ID as the probe ID column and Description as the gene symbol column\n", "mapping_df = get_gene_mapping(gene_annotation, 'ID', 'Description')\n", "\n", "# Print a preview of the mapping data\n", "print(\"\\nPreview of gene mapping data:\")\n", "print(preview_df(mapping_df))\n", "\n", "# 2. Apply the gene mapping to convert probe-level measurements to gene-level expression\n", "gene_data = apply_gene_mapping(gene_data, mapping_df)\n", "\n", "# 3. Preview the resulting gene expression data\n", "print(\"\\nPreview of gene-level expression data:\")\n", "print(f\"Shape: {gene_data.shape}\")\n", "print(f\"Number of genes: {len(gene_data)}\")\n", "print(f\"First 5 gene symbols: {list(gene_data.index[:5])}\")\n", "print(f\"First 5 samples: {list(gene_data.columns[:5])}\")\n", "\n", "# 4. Save the gene data to file\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\"\\nGene expression data saved to {out_gene_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "8763b140", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "897986a9", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:57:46.457913Z", "iopub.status.busy": "2025-03-25T07:57:46.457798Z", "iopub.status.idle": "2025-03-25T07:57:47.103236Z", "shell.execute_reply": "2025-03-25T07:57:47.102851Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Shape of gene data after normalization: (2360, 48)\n", "Saved normalized gene data to ../../output/preprocess/Mesothelioma/gene_data/GSE117668.csv\n", "Number of samples: 48\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Sample characteristics dictionary:\n", "{0: ['cell type: lung epithelial cells', 'cell type: fibroblasts', 'cell type: endothelial cells', 'cell type: peritoneal mesothelial cells', 'cell type: MPM cell line'], 1: ['diagnosis: healthy', 'diagnosis: malignant pleural mesothelioma\\xa0']}\n", "Clinical data preview:\n", " Mesothelioma\n", "GSM3305861 1\n", "GSM3305862 1\n", "GSM3305863 1\n", "GSM3305864 1\n", "GSM3305865 1\n", "Saved clinical data to ../../output/preprocess/Mesothelioma/clinical_data/GSE117668.csv\n", "Shape of linked data: (48, 2361)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Shape of linked data after handling missing values: (48, 2361)\n", "Quartiles for 'Mesothelioma':\n", " 25%: 1.0\n", " 50% (Median): 1.0\n", " 75%: 1.0\n", "Min: 1\n", "Max: 1\n", "The distribution of the feature 'Mesothelioma' in this dataset is severely biased.\n", "\n", "Dataset validation failed due to biased trait variable. Final linked data not saved.\n" ] } ], "source": [ "# 1. Normalize gene symbols in the gene expression data\n", "gene_data_normalized = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"Shape of gene data after normalization: {gene_data_normalized.shape}\")\n", "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", "gene_data_normalized.to_csv(out_gene_data_file)\n", "print(f\"Saved normalized gene data to {out_gene_data_file}\")\n", "\n", "# 2. Create clinical data from the sample IDs in the gene expression data\n", "# Since all samples are from tumor tissue, they all have mesothelioma (but this is not useful as a trait)\n", "sample_ids = gene_data.columns.tolist()\n", "print(f\"Number of samples: {len(sample_ids)}\")\n", "\n", "# Extract gender information from the original matrix file\n", "gender_data = {}\n", "try:\n", " soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", " \n", " # Read the matrix file to extract sample characteristics\n", " background_info, clinical_data = get_background_and_clinical_data(matrix_file)\n", " \n", " # Display unique values in each row of clinical data\n", " characteristics_dict = get_unique_values_by_row(clinical_data)\n", " print(\"Sample characteristics dictionary:\")\n", " print(characteristics_dict)\n", " \n", " # Try to find gender information in the characteristics\n", " gender_row = None\n", " for idx, values in characteristics_dict.items():\n", " if any('sex:' in str(v).lower() for v in values):\n", " gender_row = idx\n", " break\n", " \n", " if gender_row is not None:\n", " # Extract gender data from the row\n", " for col in clinical_data.columns:\n", " if col != '!Sample_geo_accession':\n", " continue\n", " \n", " for idx, row in clinical_data.iterrows():\n", " if idx == gender_row:\n", " for i, sample_id in enumerate(clinical_data.iloc[0].values):\n", " if i > 0 and sample_id in sample_ids: # Skip the first column (header)\n", " gender_val = clinical_data.iloc[idx, i]\n", " if isinstance(gender_val, str) and 'sex:' in gender_val.lower():\n", " gender = 0 if 'f' in gender_val.lower() else 1 if 'm' in gender_val.lower() else None\n", " gender_data[sample_id] = gender\n", "except Exception as e:\n", " print(f\"Error extracting gender data: {e}\")\n", "\n", "# Create a clinical dataframe\n", "clinical_df = pd.DataFrame(index=sample_ids)\n", "clinical_df['Mesothelioma'] = 1 # All samples have mesothelioma\n", "\n", "# Add gender if available\n", "if gender_data:\n", " clinical_df['Gender'] = clinical_df.index.map(lambda x: gender_data.get(x))\n", " print(f\"Added gender data for {sum(pd.notna(clinical_df['Gender']))} samples\")\n", "\n", "print(\"Clinical data preview:\")\n", "print(clinical_df.head())\n", "\n", "# Save the clinical data\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\"Saved clinical data to {out_clinical_data_file}\")\n", "\n", "# 3. Link clinical and genetic data (transpose gene expression data to have samples as rows)\n", "linked_data = pd.concat([clinical_df, gene_data_normalized.T], axis=1)\n", "print(f\"Shape of linked data: {linked_data.shape}\")\n", "\n", "# 4. Handle missing values in the linked data\n", "linked_data_cleaned = handle_missing_values(linked_data, 'Mesothelioma')\n", "print(f\"Shape of linked data after handling missing values: {linked_data_cleaned.shape}\")\n", "\n", "# 5. Check if the trait is biased (it will be since all samples are mesothelioma)\n", "is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data_cleaned, 'Mesothelioma')\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, # We do have trait data, it's just that all values are the same\n", " is_biased=is_trait_biased, # This will be True since all samples have the same trait value\n", " df=unbiased_linked_data,\n", " note=\"Dataset contains gene expression data from mesothelioma patients only (no controls), making trait biased.\"\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 due to biased trait variable. 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 }