{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "1353123c", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:57:16.000345Z", "iopub.status.busy": "2025-03-25T07:57:16.000110Z", "iopub.status.idle": "2025-03-25T07:57:16.168840Z", "shell.execute_reply": "2025-03-25T07:57:16.168516Z" } }, "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 = \"GSE107754\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Mesothelioma\"\n", "in_cohort_dir = \"../../input/GEO/Mesothelioma/GSE107754\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Mesothelioma/GSE107754.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Mesothelioma/gene_data/GSE107754.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Mesothelioma/clinical_data/GSE107754.csv\"\n", "json_path = \"../../output/preprocess/Mesothelioma/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "06686e29", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "138321cc", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:57:16.170334Z", "iopub.status.busy": "2025-03-25T07:57:16.170183Z", "iopub.status.idle": "2025-03-25T07:57:16.397052Z", "shell.execute_reply": "2025-03-25T07:57:16.396682Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Files in the directory:\n", "['GSE107754_family.soft.gz', 'GSE107754_series_matrix.txt.gz']\n", "SOFT file: ../../input/GEO/Mesothelioma/GSE107754/GSE107754_family.soft.gz\n", "Matrix file: ../../input/GEO/Mesothelioma/GSE107754/GSE107754_series_matrix.txt.gz\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"A novel genomic signature predicting FDG uptake in diverse metastatic tumors\"\n", "!Series_summary\t\"Purpose: Building a universal genomic signature predicting the intensity of FDG uptake in diverse metastatic tumors may allow us to understand better the biological processes underlying this phenomenon and their requirements of glucose uptake.\"\n", "!Series_summary\t\"Methods: A balanced training set (n=71) of metastatic tumors including some of the most frequent histologies, with matched PET/CT quantification measurements and whole human genome gene expression microarrays, was used to build the signature. Selection of microarray features was carried out exclusively on the basis of their strong association with FDG uptake (as measured by SUVmean35) by means of univariate linear regression. A thorough bioinformatics study of these genes was performed and multivariable models were built by fitting several state of the art regression techniques to the training set for comparison.\"\n", "!Series_summary\t\"Results: The 909 probes with the strongest association with the SUVmean35 (comprising 742 identifiable genes and 62 probes not matched to a symbol) were used to build the signature. Partial Least Squares using 3 components (PLS-3) was the best performing model in the training dataset cross-validation (Root Mean Square Error, RMSE=0.443) and was validated further in an independent validation dataset (n=13) obtaining a performance within the 95% CI of that obtained in the training dataset (RMSE=0.645). Significantly overrepresented biological processes correlating with the SUVmean35 were identified beyond glycolysis, such as ribosome biogenesis and DNA replication (correlating with a higher SUVmean35), and cytoskeleton reorganization and autophagy (correlating with a lower SUVmean35), among others.\"\n", "!Series_summary\t\"Conclusions: PLS-3 is a signature predicting accurately the intensity of FDG uptake in diverse metastatic tumors. FDG-PET might help in the design of specific targeted therapies directed to counteract the identified malignant biological processes more likely activated in a tumor as inferred from the SUVmean35 and also from its variations in response to antineoplastic treatments.\"\n", "!Series_overall_design\t\"Whole human genome microarrays from biopsies of human metastatic tumors (71 patients) with matched SUVmean35 measurements, this submission includes the 71 patients of the training set used to build the genomic signature predicting FDG uptake in diverse metastatic tumors. This dataset is complemented with a validation set comprised of 13 patients.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['gender: Male', 'gender: Female'], 1: ['dataset: Validation set', 'dataset: Training set'], 2: ['biopsy location: Lung', 'biopsy location: Lymph node', 'biopsy location: Primary', 'biopsy location: Liver', 'biopsy location: Retroperitoneal implant', 'tissue: Pancreatic cancer', 'tissue: Esophagus cancer', 'tissue: Breast cancer', 'tissue: Colorectal cancer', 'tissue: Ovarian cancer', 'tissue: Head&neck cancer', 'tissue: Lung cancer', 'tissue: Malignant Melanoma', 'tissue: Endometrial cancer', 'tissue: Cervix cancer', 'tissue: Soft tissue sarcoma', 'tissue: Gastric cancer', 'tissue: Unknown primary', 'tissue: Malignant Mesothelioma', 'tissue: Thyroid cancer', 'tissue: Testes cancer', 'tissue: Non Hodgkin lymphoma', 'tissue: Merkel cell carcinoma', 'tissue: Vaginal cancer', 'tissue: Kidney cancer', 'tissue: Cervical cancer', 'tissue: Bile duct cancer', 'tissue: Urothelial cancer'], 3: ['suvmean35: 4.09', 'suvmean35: 8.36', 'suvmean35: 5.18', 'suvmean35: 10.74', 'suvmean35: 8.62', 'suvmean35: 8.02', 'suvmean35: 6.87', 'suvmean35: 4.93', 'suvmean35: 1.96', 'suvmean35: 8.83', 'suvmean35: 3.96', 'suvmean35: 3.38', 'suvmean35: 9.95', 'suvmean35: 5.19', 'suvmean35: 7.22', 'suvmean35: 5.02', 'suvmean35: 4.92', 'suvmean35: 4.99', 'suvmean35: 4.01', 'suvmean35: 2.52', 'suvmean35: 5.52', 'suvmean35: 8.38', 'suvmean35: 3.46', 'suvmean35: 4.07', 'suvmean35: 4.67', 'suvmean35: 7.09', 'suvmean35: 4.83', 'suvmean35: 6.7', 'suvmean35: 3.95', 'suvmean35: 5.03']}\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": "0cc25299", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "8d0bb5e7", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:57:16.398379Z", "iopub.status.busy": "2025-03-25T07:57:16.398261Z", "iopub.status.idle": "2025-03-25T07:57:16.413464Z", "shell.execute_reply": "2025-03-25T07:57:16.413155Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Preview of clinical features: {'\"GSM2878070\"': [0.0, nan], '\"GSM2878071\"': [0.0, nan], '\"GSM2878072\"': [0.0, nan], '\"GSM2878073\"': [0.0, nan], '\"GSM2878074\"': [0.0, nan], '\"GSM2878075\"': [0.0, nan], '\"GSM2878076\"': [0.0, nan], '\"GSM2878077\"': [0.0, nan], '\"GSM2878078\"': [0.0, nan], '\"GSM2878079\"': [0.0, nan], '\"GSM2878080\"': [0.0, nan], '\"GSM2878081\"': [0.0, nan], '\"GSM2878082\"': [0.0, nan], '\"GSM2891194\"': [0.0, nan], '\"GSM2891195\"': [0.0, nan], '\"GSM2891196\"': [0.0, nan], '\"GSM2891197\"': [0.0, nan], '\"GSM2891198\"': [0.0, nan], '\"GSM2891199\"': [0.0, nan], '\"GSM2891200\"': [0.0, nan], '\"GSM2891201\"': [0.0, nan], '\"GSM2891202\"': [0.0, nan], '\"GSM2891203\"': [0.0, nan], '\"GSM2891204\"': [0.0, nan], '\"GSM2891205\"': [0.0, nan], '\"GSM2891206\"': [0.0, nan], '\"GSM2891207\"': [0.0, nan], '\"GSM2891208\"': [0.0, nan], '\"GSM2891209\"': [0.0, nan], '\"GSM2891210\"': [0.0, nan], '\"GSM2891211\"': [0.0, nan], '\"GSM2891212\"': [0.0, nan], '\"GSM2891213\"': [0.0, nan], '\"GSM2891214\"': [0.0, nan], '\"GSM2891215\"': [0.0, nan], '\"GSM2891216\"': [0.0, nan], '\"GSM2891217\"': [1.0, nan], '\"GSM2891218\"': [0.0, nan], '\"GSM2891219\"': [0.0, nan], '\"GSM2891220\"': [0.0, nan], '\"GSM2891221\"': [0.0, nan], '\"GSM2891222\"': [0.0, nan], '\"GSM2891223\"': [0.0, nan], '\"GSM2891224\"': [0.0, nan], '\"GSM2891225\"': [0.0, nan], '\"GSM2891226\"': [0.0, nan], '\"GSM2891227\"': [0.0, nan], '\"GSM2891228\"': [0.0, nan], '\"GSM2891229\"': [0.0, nan], '\"GSM2891230\"': [0.0, nan], '\"GSM2891231\"': [0.0, nan], '\"GSM2891232\"': [0.0, nan], '\"GSM2891233\"': [0.0, nan], '\"GSM2891234\"': [0.0, nan], '\"GSM2891235\"': [0.0, nan], '\"GSM2891236\"': [0.0, nan], '\"GSM2891237\"': [0.0, nan], '\"GSM2891238\"': [0.0, nan], '\"GSM2891239\"': [0.0, nan], '\"GSM2891240\"': [0.0, nan], '\"GSM2891241\"': [0.0, nan], '\"GSM2891242\"': [0.0, nan], '\"GSM2891243\"': [0.0, nan], '\"GSM2891244\"': [0.0, nan], '\"GSM2891245\"': [0.0, nan], '\"GSM2891246\"': [0.0, nan], '\"GSM2891247\"': [0.0, nan], '\"GSM2891248\"': [0.0, nan], '\"GSM2891249\"': [0.0, nan], '\"GSM2891250\"': [0.0, nan], '\"GSM2891251\"': [0.0, nan], '\"GSM2891252\"': [0.0, nan], '\"GSM2891253\"': [0.0, nan], '\"GSM2891254\"': [0.0, nan], '\"GSM2891255\"': [0.0, nan], '\"GSM2891256\"': [0.0, nan], '\"GSM2891257\"': [0.0, nan], '\"GSM2891258\"': [0.0, nan], '\"GSM2891259\"': [0.0, nan], '\"GSM2891260\"': [0.0, nan], '\"GSM2891261\"': [0.0, nan], '\"GSM2891262\"': [0.0, nan], '\"GSM2891263\"': [0.0, nan], '\"GSM2891264\"': [0.0, nan]}\n", "Clinical features saved to ../../output/preprocess/Mesothelioma/clinical_data/GSE107754.csv\n" ] } ], "source": [ "import pandas as pd\n", "import os\n", "import json\n", "import gzip\n", "from typing import Optional, Callable, Dict, Any\n", "import re\n", "\n", "# 1. Gene Expression Data Availability\n", "# Based on the information provided, this dataset appears to contain gene expression data\n", "# as mentioned in the series summary: \"whole human genome gene expression microarrays\"\n", "is_gene_available = True\n", "\n", "# 2.1 Data Availability\n", "# For trait (Mesothelioma), looking at row 2 which contains tissue types\n", "# We can see \"tissue: Malignant Mesothelioma\" is available\n", "trait_row = 2\n", "\n", "# Age is not available in the sample characteristics\n", "age_row = None\n", "\n", "# Gender is available in row 0\n", "gender_row = 0\n", "\n", "# 2.2 Data Type Conversion\n", "def convert_trait(value: str) -> Optional[int]:\n", " \"\"\"\n", " Convert tissue type to binary: 1 if Mesothelioma, 0 otherwise\n", " \"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract the value after the colon\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " # Check if it's Mesothelioma (case-insensitive)\n", " if re.search(r'malignant\\s+mesothelioma', value, re.IGNORECASE):\n", " return 1\n", " else:\n", " return 0\n", "\n", "def convert_age(value: str) -> Optional[float]:\n", " \"\"\"\n", " Convert age to float. Not used in this dataset as age is not available.\n", " \"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract the value after the colon\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " try:\n", " return float(value)\n", " except (ValueError, TypeError):\n", " return None\n", "\n", "def convert_gender(value: str) -> Optional[int]:\n", " \"\"\"\n", " Convert gender to binary: 0 for female, 1 for male\n", " \"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract the value after the colon\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip().lower()\n", " \n", " if value == \"male\":\n", " return 1\n", " elif value == \"female\":\n", " return 0\n", " else:\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Check if trait data is available (trait_row is not None)\n", "is_trait_available = trait_row is not None\n", "\n", "# Conduct initial filtering on the usability of the dataset\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", " # Parse the series matrix file to extract clinical data\n", " matrix_file_path = os.path.join(in_cohort_dir, \"GSE107754_series_matrix.txt.gz\")\n", " \n", " samples = []\n", " characteristics = []\n", " \n", " with gzip.open(matrix_file_path, 'rt') as f:\n", " for line in f:\n", " if line.startswith('!Sample_geo_accession'):\n", " samples = line.strip().split('\\t')[1:]\n", " elif line.startswith('!Sample_characteristics_ch1'):\n", " characteristics.append(line.strip().split('\\t')[1:])\n", " # Stop once we've passed the characteristics section\n", " elif samples and characteristics and not line.startswith('!Sample_'):\n", " break\n", " \n", " # Create a DataFrame with samples as columns and characteristics as rows\n", " if samples and characteristics:\n", " clinical_data = pd.DataFrame(characteristics, columns=samples)\n", " \n", " # Extract clinical features\n", " clinical_features = 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)\n", " print(\"Preview of clinical features:\", preview)\n", " \n", " # Create directory if it doesn't exist\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " \n", " # Save the clinical features to CSV\n", " clinical_features.to_csv(out_clinical_data_file)\n", " print(f\"Clinical features saved to {out_clinical_data_file}\")\n", " else:\n", " print(\"Could not extract sample information or characteristics from the matrix file.\")\n" ] }, { "cell_type": "markdown", "id": "70c0b753", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "4e5ab82b", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:57:16.414618Z", "iopub.status.busy": "2025-03-25T07:57:16.414507Z", "iopub.status.idle": "2025-03-25T07:57:16.804454Z", "shell.execute_reply": "2025-03-25T07:57:16.804064Z" } }, "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: 41000\n", "First 20 gene/probe identifiers:\n", "Index(['A_23_P100001', 'A_23_P100011', 'A_23_P100022', 'A_23_P100056',\n", " 'A_23_P100074', 'A_23_P100092', 'A_23_P100103', 'A_23_P100111',\n", " 'A_23_P100127', 'A_23_P100133', 'A_23_P100141', 'A_23_P100156',\n", " 'A_23_P100177', 'A_23_P100189', 'A_23_P100196', 'A_23_P100203',\n", " 'A_23_P100220', 'A_23_P100240', 'A_23_P10025', 'A_23_P100263'],\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": "c029adc1", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "435ed6c8", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:57:16.805747Z", "iopub.status.busy": "2025-03-25T07:57:16.805630Z", "iopub.status.idle": "2025-03-25T07:57:16.807560Z", "shell.execute_reply": "2025-03-25T07:57:16.807273Z" } }, "outputs": [], "source": [ "# Looking at the gene identifiers from the previous step\n", "# These identifiers like 'A_23_P100001' appear to be Agilent microarray probe IDs, not human gene symbols\n", "# These need to be mapped to official gene symbols for biological interpretation\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "33cdff2b", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "1814835e", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:57:16.808707Z", "iopub.status.busy": "2025-03-25T07:57:16.808600Z", "iopub.status.idle": "2025-03-25T07:57:21.928651Z", "shell.execute_reply": "2025-03-25T07:57:21.928220Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene annotation preview:\n", "{'ID': ['A_23_P100001', 'A_23_P100011', 'A_23_P100022', 'A_23_P100056', 'A_23_P100074'], 'SPOT_ID': ['A_23_P100001', 'A_23_P100011', 'A_23_P100022', 'A_23_P100056', 'A_23_P100074'], 'CONTROL_TYPE': ['FALSE', 'FALSE', 'FALSE', 'FALSE', 'FALSE'], 'REFSEQ': ['NM_207446', 'NM_005829', 'NM_014848', 'NM_194272', 'NM_020371'], 'GB_ACC': ['NM_207446', 'NM_005829', 'NM_014848', 'NM_194272', 'NM_020371'], 'GENE': [400451.0, 10239.0, 9899.0, 348093.0, 57099.0], 'GENE_SYMBOL': ['FAM174B', 'AP3S2', 'SV2B', 'RBPMS2', 'AVEN'], 'GENE_NAME': ['family with sequence similarity 174, member B', 'adaptor-related protein complex 3, sigma 2 subunit', 'synaptic vesicle glycoprotein 2B', 'RNA binding protein with multiple splicing 2', 'apoptosis, caspase activation inhibitor'], 'UNIGENE_ID': ['Hs.27373', 'Hs.632161', 'Hs.21754', 'Hs.436518', 'Hs.555966'], 'ENSEMBL_ID': ['ENST00000557398', nan, 'ENST00000557410', 'ENST00000300069', 'ENST00000306730'], 'TIGR_ID': [nan, nan, nan, nan, nan], 'ACCESSION_STRING': ['ref|NM_207446|ens|ENST00000557398|ens|ENST00000553393|ens|ENST00000327355', 'ref|NM_005829|ref|NM_001199058|ref|NR_023361|ref|NR_037582', 'ref|NM_014848|ref|NM_001167580|ens|ENST00000557410|ens|ENST00000330276', 'ref|NM_194272|ens|ENST00000300069|gb|AK127873|gb|AK124123', 'ref|NM_020371|ens|ENST00000306730|gb|AF283508|gb|BC010488'], 'CHROMOSOMAL_LOCATION': ['chr15:93160848-93160789', 'chr15:90378743-90378684', 'chr15:91838329-91838388', 'chr15:65032375-65032316', 'chr15:34158739-34158680'], 'CYTOBAND': ['hs|15q26.1', 'hs|15q26.1', 'hs|15q26.1', 'hs|15q22.31', 'hs|15q14'], 'DESCRIPTION': ['Homo sapiens family with sequence similarity 174, member B (FAM174B), mRNA [NM_207446]', 'Homo sapiens adaptor-related protein complex 3, sigma 2 subunit (AP3S2), transcript variant 1, mRNA [NM_005829]', 'Homo sapiens synaptic vesicle glycoprotein 2B (SV2B), transcript variant 1, mRNA [NM_014848]', 'Homo sapiens RNA binding protein with multiple splicing 2 (RBPMS2), mRNA [NM_194272]', 'Homo sapiens apoptosis, caspase activation inhibitor (AVEN), mRNA [NM_020371]'], 'GO_ID': ['GO:0016020(membrane)|GO:0016021(integral to membrane)', 'GO:0005794(Golgi apparatus)|GO:0006886(intracellular protein transport)|GO:0008565(protein transporter activity)|GO:0016020(membrane)|GO:0016192(vesicle-mediated transport)|GO:0030117(membrane coat)|GO:0030659(cytoplasmic vesicle membrane)|GO:0031410(cytoplasmic vesicle)', 'GO:0001669(acrosomal vesicle)|GO:0006836(neurotransmitter transport)|GO:0016020(membrane)|GO:0016021(integral to membrane)|GO:0022857(transmembrane transporter activity)|GO:0030054(cell junction)|GO:0030672(synaptic vesicle membrane)|GO:0031410(cytoplasmic vesicle)|GO:0045202(synapse)', 'GO:0000166(nucleotide binding)|GO:0003676(nucleic acid binding)', 'GO:0005515(protein binding)|GO:0005622(intracellular)|GO:0005624(membrane fraction)|GO:0006915(apoptosis)|GO:0006916(anti-apoptosis)|GO:0012505(endomembrane system)|GO:0016020(membrane)'], 'SEQUENCE': ['ATCTCATGGAAAAGCTGGATTCCTCTGCCTTACGCAGAAACACCCGGGCTCCATCTGCCA', 'TCAAGTATTGGCCTGACATAGAGTCCTTAAGACAAGCAAAGACAAGCAAGGCAAGCACGT', 'ATGTCGGCTGTGGAGGGTTAAAGGGATGAGGCTTTCCTTTGTTTAGCAAATCTGTTCACA', 'CCCTGTCAGATAAGTTTAATGTTTAGTTTGAGGCATGAAGAAGAAAAGGGTTTCCATTCT', 'GACCAGCCAGTTTACAAGCATGTCTCAAGCTAGTGTGTTCCATTATGCTCACAGCAGTAA']}\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": "dc6ca093", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "2c2fb768", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:57:21.930351Z", "iopub.status.busy": "2025-03-25T07:57:21.930111Z", "iopub.status.idle": "2025-03-25T07:57:23.196366Z", "shell.execute_reply": "2025-03-25T07:57:23.195967Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene mapping preview:\n", "{'ID': ['A_23_P100001', 'A_23_P100011', 'A_23_P100022', 'A_23_P100056', 'A_23_P100074'], 'Gene': ['FAM174B', 'AP3S2', 'SV2B', 'RBPMS2', 'AVEN']}\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene expression data after mapping:\n", "Number of genes: 18488\n", "First 5 gene symbols:\n", "Index(['A1BG', 'A1BG-AS1', 'A1CF', 'A2LD1', 'A2M'], dtype='object', name='Gene')\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data saved to ../../output/preprocess/Mesothelioma/gene_data/GSE107754.csv\n" ] } ], "source": [ "# 1. Observing the gene identifiers in the gene expression data:\n", "# From step 3, we see identifiers like 'A_23_P100001' \n", "# From step 5, we see the same identifiers in the 'ID' column of gene_annotation dataframe\n", "# The gene symbols are stored in the 'GENE_SYMBOL' column\n", "\n", "# 2. Get a gene mapping dataframe\n", "probe_col = 'ID' # Column with probe identifiers\n", "gene_col = 'GENE_SYMBOL' # Column with gene symbols\n", "gene_mapping = get_gene_mapping(gene_annotation, probe_col, gene_col)\n", "\n", "print(\"Gene mapping preview:\")\n", "print(preview_df(gene_mapping))\n", "\n", "# 3. Convert probe-level measurements to gene expression data\n", "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n", "\n", "print(\"\\nGene expression data after mapping:\")\n", "print(\"Number of genes:\", len(gene_data))\n", "print(\"First 5 gene symbols:\")\n", "print(gene_data.index[:5])\n", "\n", "# Save gene expression 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\"Gene expression data saved to {out_gene_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "bff1f710", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "5c746dbf", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:57:23.197883Z", "iopub.status.busy": "2025-03-25T07:57:23.197616Z", "iopub.status.idle": "2025-03-25T07:57:29.581128Z", "shell.execute_reply": "2025-03-25T07:57:29.580588Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Shape of gene data after normalization: (18247, 84)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Saved normalized gene data to ../../output/preprocess/Mesothelioma/gene_data/GSE107754.csv\n", "Number of samples: 84\n", "Sample characteristics dictionary:\n", "{0: ['gender: Male', 'gender: Female'], 1: ['dataset: Validation set', 'dataset: Training set'], 2: ['biopsy location: Lung', 'biopsy location: Lymph node', 'biopsy location: Primary', 'biopsy location: Liver', 'biopsy location: Retroperitoneal implant', 'tissue: Pancreatic cancer', 'tissue: Esophagus cancer', 'tissue: Breast cancer', 'tissue: Colorectal cancer', 'tissue: Ovarian cancer', 'tissue: Head&neck cancer', 'tissue: Lung cancer', 'tissue: Malignant Melanoma', 'tissue: Endometrial cancer', 'tissue: Cervix cancer', 'tissue: Soft tissue sarcoma', 'tissue: Gastric cancer', 'tissue: Unknown primary', 'tissue: Malignant Mesothelioma', 'tissue: Thyroid cancer', 'tissue: Testes cancer', 'tissue: Non Hodgkin lymphoma', 'tissue: Merkel cell carcinoma', 'tissue: Vaginal cancer', 'tissue: Kidney cancer', 'tissue: Cervical cancer', 'tissue: Bile duct cancer', 'tissue: Urothelial cancer'], 3: ['suvmean35: 4.09', 'suvmean35: 8.36', 'suvmean35: 5.18', 'suvmean35: 10.74', 'suvmean35: 8.62', 'suvmean35: 8.02', 'suvmean35: 6.87', 'suvmean35: 4.93', 'suvmean35: 1.96', 'suvmean35: 8.83', 'suvmean35: 3.96', 'suvmean35: 3.38', 'suvmean35: 9.95', 'suvmean35: 5.19', 'suvmean35: 7.22', 'suvmean35: 5.02', 'suvmean35: 4.92', 'suvmean35: 4.99', 'suvmean35: 4.01', 'suvmean35: 2.52', 'suvmean35: 5.52', 'suvmean35: 8.38', 'suvmean35: 3.46', 'suvmean35: 4.07', 'suvmean35: 4.67', 'suvmean35: 7.09', 'suvmean35: 4.83', 'suvmean35: 6.7', 'suvmean35: 3.95', 'suvmean35: 5.03']}\n", "Clinical data preview:\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ " Mesothelioma\n", "GSM2878070 1\n", "GSM2878071 1\n", "GSM2878072 1\n", "GSM2878073 1\n", "GSM2878074 1\n", "Saved clinical data to ../../output/preprocess/Mesothelioma/clinical_data/GSE107754.csv\n", "Shape of linked data: (84, 18248)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Shape of linked data after handling missing values: (84, 18248)\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", "A new JSON file was created at: ../../output/preprocess/Mesothelioma/cohort_info.json\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 }