{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "c90ba22f", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:09:22.661027Z", "iopub.status.busy": "2025-03-25T04:09:22.660909Z", "iopub.status.idle": "2025-03-25T04:09:22.829264Z", "shell.execute_reply": "2025-03-25T04:09:22.828761Z" } }, "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 = \"Thymoma\"\n", "cohort = \"GSE42977\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Thymoma\"\n", "in_cohort_dir = \"../../input/GEO/Thymoma/GSE42977\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Thymoma/GSE42977.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Thymoma/gene_data/GSE42977.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Thymoma/clinical_data/GSE42977.csv\"\n", "json_path = \"../../output/preprocess/Thymoma/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "edcef6f7", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "cdd9814a", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:09:22.830913Z", "iopub.status.busy": "2025-03-25T04:09:22.830747Z", "iopub.status.idle": "2025-03-25T04:09:23.144870Z", "shell.execute_reply": "2025-03-25T04:09:23.144369Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Files in the directory:\n", "['GSE42977_family.soft.gz', 'GSE42977_series_matrix.txt.gz']\n", "SOFT file: ../../input/GEO/Thymoma/GSE42977/GSE42977_family.soft.gz\n", "Matrix file: ../../input/GEO/Thymoma/GSE42977/GSE42977_series_matrix.txt.gz\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Sequential Binary Gene-Ratio Tests Define a Novel Molecular Diagnostic Strategy for Malignant Pleural Mesothelioma\"\n", "!Series_summary\t\"The gene-expression ratio technique was used to design a molecular signature to diagnose MPM from among other potentially confounding diagnoses and differentiate the epithelioid from the sarcomatoid histological subtype of MPM.\"\n", "!Series_overall_design\t\"Microarray analysis was performed on 113 specimens including MPMs and a spectrum of tumors and benign tissues comprising the differential diagnosis of MPM. A sequential combination of binary gene-expression ratio tests was developed to discriminate MPM from other thoracic malignancies . This method was compared to other bioinformatic tools and this signature was validated in an independent set of 170 samples. Functional enrichment analysis was performed to identify differentially expressed probes.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['tissue: control', 'tissue: Spindle Cell Sarcoma', 'tissue: Sarcoma', 'tissue: Metastatic Melanoma', 'tissue: Pleomorphic Sarcoma', 'tissue: Renal Cell Carcinoma-Clear Cell', 'tissue: Synovial Sarcoma', 'tissue: Metastatic Thymoma', 'tissue: Metastatic Prostate Cancer', 'tissue: Stomach Cancer-Stromal Sarcoma', 'tissue: Non-Hodgkins Lymphoma', 'tissue: Hemangioendothelioma', 'tissue: Papillary Thyroid Carcinoma', 'tissue: Metastatic Thyroid Cancer', 'tissue: Lymphocytic Lymphoma', 'tissue: Thymoma', 'tissue: Melanoma-Malignant', 'tissue: Hemangiopericytoma', 'tissue: Thyroid Carcinoma', 'tissue: Monophasic Synovial Sarcoma', 'tissue: Metastatic Alveolar Soft Part Sarcoma', 'tissue: Metastatic Meningeal Hemangiopericytoma', 'tissue: Follicular Lymphoma', 'tissue: Rhabdomyosarcoma', 'tissue: Myofibrosarcoma', 'tissue: Renal Cell Carcinoma - Chromophobe', 'tissue: MPM Epithelioid', 'tissue: MPM Sarcomatoid', 'tissue: MPM Biphasic', 'tissue: Normal Lung']}\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": "1963246f", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "c4c01e40", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:09:23.146404Z", "iopub.status.busy": "2025-03-25T04:09:23.146280Z", "iopub.status.idle": "2025-03-25T04:09:23.415302Z", "shell.execute_reply": "2025-03-25T04:09:23.414765Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Clinical data preview:\n", "{0: [0]}\n", "Clinical data saved to ../../output/preprocess/Thymoma/clinical_data/GSE42977.csv\n" ] } ], "source": [ "import pandas as pd\n", "import os\n", "import json\n", "from typing import Callable, Optional, Dict, Any, Union\n", "import numpy as np\n", "\n", "# GEO matrix files require special handling due to their format\n", "# First, identify where the actual data begins (after the metadata)\n", "data_start_line = 0\n", "with gzip.open(f\"{in_cohort_dir}/GSE42977_series_matrix.txt.gz\", 'rt') as file:\n", " for i, line in enumerate(file):\n", " if line.startswith('!Sample_'):\n", " data_start_line = i\n", " break\n", "\n", "# Read the sample characteristics table from the matrix file\n", "sample_data_lines = []\n", "with gzip.open(f\"{in_cohort_dir}/GSE42977_series_matrix.txt.gz\", 'rt') as file:\n", " for i, line in enumerate(file):\n", " if line.startswith('!Sample_characteristics_ch1'):\n", " sample_data_lines.append(line.strip())\n", "\n", "# Process the sample characteristics to create a dataframe\n", "clinical_data = {}\n", "for i, line in enumerate(sample_data_lines):\n", " # Extract the values after \"!Sample_characteristics_ch1\\t\"\n", " values = line.replace('!Sample_characteristics_ch1\\t', '').split('\\t')\n", " if i == 0: # First line - initialize the dictionary with column names\n", " for j, val in enumerate(values):\n", " clinical_data[f'Sample_{j}'] = []\n", " \n", " # Add values to the dictionary\n", " for j, val in enumerate(values):\n", " if j < len(clinical_data): # Ensure we don't exceed the initialized columns\n", " clinical_data[f'Sample_{j}'].append(val)\n", "\n", "# Convert to DataFrame and transpose to get samples as rows\n", "clinical_df = pd.DataFrame(clinical_data).transpose()\n", "\n", "# 1. Gene Expression Data Availability\n", "# Based on the series title and overall design, this appears to be a microarray gene expression dataset\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "\n", "# For trait (Thymoma), we can see 'tissue: Thymoma' and 'tissue: Metastatic Thymoma' in the characteristics\n", "# at index 0, so we can use this to identify Thymoma cases\n", "trait_row = 0 # First row contains tissue type information\n", "\n", "# Age is not mentioned in the sample characteristics\n", "age_row = None\n", "\n", "# Gender is not mentioned in the sample characteristics\n", "gender_row = None\n", "\n", "# 2.2 Data Type Conversion\n", "def convert_trait(value: str) -> Union[int, None]:\n", " \"\"\"\n", " Convert tissue type to binary (1 for Thymoma, 0 for other)\n", " \"\"\"\n", " if pd.isna(value) or not isinstance(value, str):\n", " return None\n", " \n", " # Extract the value part after the colon\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Check if the value contains \"Thymoma\"\n", " if \"Thymoma\" in value:\n", " return 1\n", " else:\n", " return 0\n", "\n", "def convert_age(value: str) -> Union[float, None]:\n", " \"\"\"\n", " Convert age to continuous numeric value\n", " Not used in this dataset but included for completeness\n", " \"\"\"\n", " return None\n", "\n", "def convert_gender(value: str) -> Union[int, None]:\n", " \"\"\"\n", " Convert gender to binary (0 for female, 1 for male)\n", " Not used in this dataset but included for completeness\n", " \"\"\"\n", " return None\n", "\n", "# 3. Save Metadata\n", "is_trait_available = trait_row is not None\n", "validate_and_save_cohort_info(\n", " is_final=False,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=is_gene_available,\n", " is_trait_available=is_trait_available\n", ")\n", "\n", "# 4. Clinical Feature Extraction\n", "if trait_row is not None:\n", " # We need to implement our own get_feature_data function since it's not provided in the library\n", " def get_feature_data(clinical_df, row_idx, feature_name, convert_func):\n", " row_data = clinical_df.iloc[row_idx]\n", " result = {}\n", " for col in clinical_df.columns:\n", " result[col] = convert_func(row_data[col])\n", " return pd.DataFrame({feature_name: result}).T\n", " \n", " # Use the function to create selected clinical features\n", " feature_list = []\n", " \n", " # Add trait data\n", " trait_data = get_feature_data(clinical_df, trait_row, trait, convert_trait)\n", " feature_list.append(trait_data)\n", " \n", " # Add age data if available\n", " if age_row is not None:\n", " age_data = get_feature_data(clinical_df, age_row, 'Age', convert_age)\n", " feature_list.append(age_data)\n", " \n", " # Add gender data if available\n", " if gender_row is not None:\n", " gender_data = get_feature_data(clinical_df, gender_row, 'Gender', convert_gender)\n", " feature_list.append(gender_data)\n", " \n", " # Combine all features\n", " selected_clinical_df = pd.concat(feature_list, axis=0)\n", " \n", " # Preview the extracted data\n", " preview = preview_df(selected_clinical_df)\n", " print(\"Clinical data preview:\")\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=False)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "580ae886", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "38018351", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:09:23.416880Z", "iopub.status.busy": "2025-03-25T04:09:23.416762Z", "iopub.status.idle": "2025-03-25T04:09:24.047762Z", "shell.execute_reply": "2025-03-25T04:09:24.047306Z" } }, "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: 46713\n", "First 20 gene/probe identifiers:\n", "Index(['ILMN_10000', 'ILMN_100000', 'ILMN_100007', 'ILMN_100009', 'ILMN_10001',\n", " 'ILMN_100010', 'ILMN_10002', 'ILMN_100028', 'ILMN_100030',\n", " 'ILMN_100031', 'ILMN_100034', 'ILMN_100037', 'ILMN_10004', 'ILMN_10005',\n", " 'ILMN_100054', 'ILMN_100059', 'ILMN_10006', 'ILMN_100075',\n", " 'ILMN_100079', 'ILMN_100083'],\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": "b96e6909", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "8e2c236f", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:09:24.049213Z", "iopub.status.busy": "2025-03-25T04:09:24.049097Z", "iopub.status.idle": "2025-03-25T04:09:24.051147Z", "shell.execute_reply": "2025-03-25T04:09:24.050774Z" } }, "outputs": [], "source": [ "# After reviewing the gene identifiers, I can conclude they are not human gene symbols\n", "# These are Illumina BeadChip probe IDs (ILMN_prefix) which need to be mapped to human gene symbols\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "b3ed2d47", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "6f628771", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:09:24.052353Z", "iopub.status.busy": "2025-03-25T04:09:24.052247Z", "iopub.status.idle": "2025-03-25T04:09:30.944883Z", "shell.execute_reply": "2025-03-25T04:09:30.944410Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene annotation preview:\n", "{'ID': ['ILMN_89282', 'ILMN_35826', 'ILMN_25544', 'ILMN_132331', 'ILMN_105017'], 'GB_ACC': ['BU678343', 'XM_497527.2', 'NM_018433.3', 'AW629334', 'AI818233'], 'Symbol': [nan, 'LOC441782', 'JMJD1A', nan, nan], 'SEQUENCE': ['CTCTCTAAAGGGACAACAGAGTGGACAGTCAAGGAACTCCACATATTCAT', 'GGGGTCAAGCCCAGGTGAAATGTGGATTGGAAAAGTGCTTCCCTTGCCCC', 'CCAGGCTGTAAAAGCAAAACCTCGTATCAGCTCTGGAACAATACCTGCAG', 'CCAGACAGGAAGCATCAAGCCCTTCAGGAAAGAATATGCGAGAGTGCTGC', 'TGTGCAGAAAGCTGATGGAAGGGAGAAAGAATGGAAGTGGGTCACACAGC'], 'Definition': ['UI-CF-EC0-abi-c-12-0-UI.s1 UI-CF-EC0 Homo sapiens cDNA clone UI-CF-EC0-abi-c-12-0-UI 3, mRNA sequence', 'PREDICTED: Homo sapiens similar to spectrin domain with coiled-coils 1 (LOC441782), mRNA.', 'Homo sapiens jumonji domain containing 1A (JMJD1A), mRNA.', 'hi56g05.x1 Soares_NFL_T_GBC_S1 Homo sapiens cDNA clone IMAGE:2976344 3, mRNA sequence', 'wk77d04.x1 NCI_CGAP_Pan1 Homo sapiens cDNA clone IMAGE:2421415 3, mRNA sequence'], 'Ontology': [nan, nan, nan, nan, nan], 'Synonym': [nan, nan, 'TSGA; JMJD1; KIAA0742; DKFZp686A24246; DKFZp686P07111', nan, nan]}\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": "87db08ae", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "54bd73f3", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:09:30.946386Z", "iopub.status.busy": "2025-03-25T04:09:30.946260Z", "iopub.status.idle": "2025-03-25T04:09:32.659835Z", "shell.execute_reply": "2025-03-25T04:09:32.659296Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Identifying probe-to-gene mapping columns:\n", "Probe ID column: 'ID'\n", "Gene symbol column: 'Symbol'\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene mapping dataframe shape: (28566, 2)\n", "First 5 rows of gene mapping:\n", " ID Gene\n", "1 ILMN_35826 LOC441782\n", "2 ILMN_25544 JMJD1A\n", "6 ILMN_10519 NCOA3\n", "8 ILMN_17234 LOC389834\n", "9 ILMN_19244 C17orf77\n", "Gene expression data shape after mapping: (18401, 117)\n", "First 5 gene symbols after mapping:\n", "Index(['A1BG', 'A2BP1', 'A2M', 'A2ML1', 'A3GALT2'], dtype='object', name='Gene')\n", "\n", "Preview of gene expression values for first 3 genes and first 3 samples:\n", " GSM1054230 GSM1054231 GSM1054232\n", "Gene \n", "A1BG 0.903276 0.821580 0.865428\n", "A2BP1 1.719921 8.432093 1.797852\n", "A2M 27.154642 17.070914 34.490890\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Mapped gene expression data saved to: ../../output/preprocess/Thymoma/gene_data/GSE42977.csv\n" ] } ], "source": [ "# 1. Examine the gene identifiers in both datasets\n", "# From previous output, gene expression data has \"ILMN_\" IDs as the index\n", "# From annotation preview, we can see that \"ID\" column contains the same ILMN identifiers\n", "# And the \"Symbol\" column contains gene symbols we want to map to\n", "\n", "print(\"Identifying probe-to-gene mapping columns:\")\n", "print(f\"Probe ID column: 'ID'\")\n", "print(f\"Gene symbol column: 'Symbol'\")\n", "\n", "# 2. Get gene mapping dataframe by extracting the relevant columns\n", "gene_mapping = get_gene_mapping(gene_annotation, 'ID', 'Symbol')\n", "print(f\"Gene mapping dataframe shape: {gene_mapping.shape}\")\n", "print(\"First 5 rows of gene mapping:\")\n", "print(gene_mapping.head())\n", "\n", "# 3. Apply the gene mapping to convert probe-level measurements to gene expression data\n", "# Using the apply_gene_mapping function from the library\n", "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n", "print(f\"Gene expression data shape after mapping: {gene_data.shape}\")\n", "print(\"First 5 gene symbols after mapping:\")\n", "print(gene_data.index[:5])\n", "\n", "# Preview some of the gene expression values\n", "print(\"\\nPreview of gene expression values for first 3 genes and first 3 samples:\")\n", "sample_cols = gene_data.columns[:3]\n", "print(gene_data.iloc[:3, :3])\n", "\n", "# Save the gene expression data to the output 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\"Mapped gene expression data saved to: {out_gene_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "6d503c96", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "116c9288", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:09:32.661416Z", "iopub.status.busy": "2025-03-25T04:09:32.661287Z", "iopub.status.idle": "2025-03-25T04:09:46.427692Z", "shell.execute_reply": "2025-03-25T04:09:46.427153Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Original gene data shape: (18401, 117)\n", "Normalized gene data shape: (17207, 117)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene expression data saved to: ../../output/preprocess/Thymoma/gene_data/GSE42977.csv\n", "Type of clinical_data: \n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Type of clinical_data after extraction: \n", "Clinical data preview:\n", "{'GSM1054230': [0.0], 'GSM1054231': [0.0], 'GSM1054232': [0.0], 'GSM1054233': [0.0], 'GSM1054234': [0.0], 'GSM1054235': [0.0], 'GSM1054236': [0.0], 'GSM1054237': [0.0], 'GSM1054238': [0.0], 'GSM1054239': [0.0], 'GSM1054240': [0.0], 'GSM1054241': [0.0], 'GSM1054242': [0.0], 'GSM1054243': [1.0], 'GSM1054244': [0.0], 'GSM1054245': [0.0], 'GSM1054246': [0.0], 'GSM1054247': [0.0], 'GSM1054248': [0.0], 'GSM1054249': [0.0], 'GSM1054250': [0.0], 'GSM1054251': [0.0], 'GSM1054252': [0.0], 'GSM1054253': [0.0], 'GSM1054254': [0.0], 'GSM1054255': [0.0], 'GSM1054256': [1.0], 'GSM1054257': [0.0], 'GSM1054258': [0.0], 'GSM1054259': [0.0], 'GSM1054260': [0.0], 'GSM1054261': [0.0], 'GSM1054262': [0.0], 'GSM1054263': [0.0], 'GSM1054264': [0.0], 'GSM1054265': [1.0], 'GSM1054266': [0.0], 'GSM1054267': [0.0], 'GSM1054268': [0.0], 'GSM1054269': [0.0], 'GSM1054270': [0.0], 'GSM1054271': [1.0], 'GSM1054272': [0.0], 'GSM1054273': [0.0], 'GSM1054274': [0.0], 'GSM1054275': [0.0], 'GSM1054276': [0.0], 'GSM1054277': [1.0], 'GSM1054278': [0.0], 'GSM1054279': [0.0], 'GSM1054280': [0.0], 'GSM1054281': [0.0], 'GSM1054282': [0.0], 'GSM1054283': [0.0], 'GSM1054284': [0.0], 'GSM1054285': [0.0], 'GSM1054286': [0.0], 'GSM1054287': [0.0], 'GSM1054288': [0.0], 'GSM1054289': [0.0], 'GSM1054290': [0.0], 'GSM1054291': [0.0], 'GSM1054292': [0.0], 'GSM1054293': [0.0], 'GSM1054294': [0.0], 'GSM1054295': [0.0], 'GSM1054296': [0.0], 'GSM1054297': [0.0], 'GSM1054298': [0.0], 'GSM1054299': [0.0], 'GSM1054300': [0.0], 'GSM1054301': [0.0], 'GSM1054302': [0.0], 'GSM1054303': [0.0], 'GSM1054304': [0.0], 'GSM1054305': [0.0], 'GSM1054306': [0.0], 'GSM1054307': [0.0], 'GSM1054308': [0.0], 'GSM1054309': [0.0], 'GSM1054310': [0.0], 'GSM1054311': [0.0], 'GSM1054312': [0.0], 'GSM1054313': [0.0], 'GSM1054314': [0.0], 'GSM1054315': [0.0], 'GSM1054316': [0.0], 'GSM1054317': [0.0], 'GSM1054318': [0.0], 'GSM1054319': [0.0], 'GSM1054320': [0.0], 'GSM1054321': [0.0], 'GSM1054322': [0.0], 'GSM1054323': [0.0], 'GSM1054324': [0.0], 'GSM1054325': [0.0], 'GSM1054326': [0.0], 'GSM1054327': [0.0], 'GSM1054328': [0.0], 'GSM1054329': [0.0], 'GSM1054330': [1.0], 'GSM1054331': [0.0], 'GSM1054332': [0.0], 'GSM1054333': [0.0], 'GSM1054334': [0.0], 'GSM1054335': [0.0], 'GSM1054336': [0.0], 'GSM1054337': [0.0], 'GSM1054338': [0.0], 'GSM1054339': [0.0], 'GSM1054340': [0.0], 'GSM1054341': [0.0], 'GSM1054342': [0.0], 'GSM1054343': [0.0], 'GSM1054344': [0.0], 'GSM1054345': [0.0], 'GSM1054346': [0.0]}\n", "Clinical data saved to ../../output/preprocess/Thymoma/clinical_data/GSE42977.csv\n", "Shape of linked data: (117, 17208)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Shape of linked data after handling missing values: (117, 17208)\n", "For the feature 'Thymoma', the least common label is '1.0' with 6 occurrences. This represents 5.13% of the dataset.\n", "The distribution of the feature 'Thymoma' in this dataset is fine.\n", "\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Saved processed linked data to ../../output/preprocess/Thymoma/GSE42977.csv\n" ] } ], "source": [ "# 1. Normalize gene symbols in the gene expression data\n", "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"Original gene data shape: {gene_data.shape}\")\n", "print(f\"Normalized gene data shape: {normalized_gene_data.shape}\")\n", "\n", "# Save the normalized gene expression data\n", "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", "normalized_gene_data.to_csv(out_gene_data_file)\n", "print(f\"Normalized gene expression data saved to: {out_gene_data_file}\")\n", "\n", "# 2. Process the clinical data based on the available information\n", "# First check what clinical_data actually is\n", "print(\"Type of clinical_data:\", type(clinical_data))\n", "\n", "# We need to extract clinical data again with the correct function\n", "try:\n", " soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", " background_info, clinical_data = get_background_and_clinical_data(matrix_file)\n", " \n", " # Verify that clinical_data is a DataFrame\n", " print(\"Type of clinical_data after extraction:\", type(clinical_data))\n", " \n", " # Define the convert_trait function specific to this dataset\n", " def convert_trait(value):\n", " \"\"\"Convert tissue type to binary (1 for Thymoma, 0 for other)\"\"\"\n", " if not isinstance(value, str):\n", " return None\n", " \n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Look for Thymoma in the value\n", " if 'Thymoma' in value:\n", " return 1\n", " else:\n", " return 0\n", " \n", " # Extract clinical features using only the available row\n", " clinical_df = geo_select_clinical_features(\n", " clinical_data,\n", " trait=trait,\n", " trait_row=0, # Only row with tissue information\n", " convert_trait=convert_trait,\n", " age_row=None, # Age not available\n", " convert_age=None,\n", " gender_row=None, # Gender not available\n", " convert_gender=None\n", " )\n", " \n", " print(\"Clinical data preview:\")\n", " print(preview_df(clinical_df))\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\"Clinical data saved to {out_clinical_data_file}\")\n", " \n", " # 3. Link clinical and genetic data\n", " linked_data = geo_link_clinical_genetic_data(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_cleaned = handle_missing_values(linked_data, trait)\n", " print(f\"Shape of linked data after handling missing values: {linked_data_cleaned.shape}\")\n", " \n", " # 5. Check if the trait and demographic features are biased\n", " is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data_cleaned, trait)\n", " \n", " # 6. Validate the dataset and save cohort information\n", " note = \"Dataset from GSE42977 focused on multiple tissue types including Thymoma. Only tissue information was available for clinical features.\"\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=note\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.\")\n", " \n", "except Exception as e:\n", " print(f\"Error in processing clinical data: {e}\")\n", " print(f\"Full error: {type(e).__name__}: {str(e)}\")\n", " \n", " # Create a minimal DataFrame for validation\n", " empty_df = pd.DataFrame({trait: []})\n", " \n", " # If clinical data processing fails, update the cohort info\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,\n", " is_biased=False, # Set a value for validation\n", " df=empty_df,\n", " note=\"Failed to extract clinical data. Gene expression data is available but clinical feature extraction failed.\"\n", " )\n", " print(\"Dataset validation failed due to missing or corrupted clinical data. Only gene data 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 }