{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "c0eece49", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:30:04.032379Z", "iopub.status.busy": "2025-03-25T07:30:04.032153Z", "iopub.status.idle": "2025-03-25T07:30:04.198817Z", "shell.execute_reply": "2025-03-25T07:30:04.198396Z" } }, "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 = \"Liver_Cancer\"\n", "cohort = \"GSE209875\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Liver_Cancer\"\n", "in_cohort_dir = \"../../input/GEO/Liver_Cancer/GSE209875\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Liver_Cancer/GSE209875.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Liver_Cancer/gene_data/GSE209875.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Liver_Cancer/clinical_data/GSE209875.csv\"\n", "json_path = \"../../output/preprocess/Liver_Cancer/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "ed2b265f", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "df6ec741", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:30:04.200092Z", "iopub.status.busy": "2025-03-25T07:30:04.199939Z", "iopub.status.idle": "2025-03-25T07:30:04.225342Z", "shell.execute_reply": "2025-03-25T07:30:04.225012Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Available files in the directory:\n", "['GSE209875-GPL21263_series_matrix.txt.gz']\n", "\n", "Background Information:\n", "!Series_title\t\"MicroRNA and mRNA expression profiles of hepatobiliary tumor patients' tissue together with those of non-tumor part tissues and serum exosomes.\"\n", "!Series_summary\t\"This SuperSeries is composed of the SubSeries listed below.\"\n", "!Series_overall_design\t\"Refer to individual Series\"\n", "\n", "Sample Characteristics Dictionary:\n", "{0: ['histology: Cholangiocarcinoma, tumor part', 'histology: Cholangiocarcinoma (less than 40 generations), tumor part', 'histology: Cholangiocarcinoma, non-tumor part', 'histology: Cholangiocarcinoma (less than 40 generations), non-tumor part', 'histology: Hepatocellular carcinoma, tumor part', 'histology: Hepatocellular carcinoma, non-tumor part', 'histology: Inflammatory pseudotumor (benign), tumor part', 'histology: Angiomyolipoma (benign), tumor part', 'histology: Adenomyomatous hyperplasia of gallbladder (benign), tumor part', 'histology: Focal nodular hyperplasia of liver (benign), tumor part', 'histology: Inflammatory pseudotumor (benign), non-tumor part', 'histology: Angiomyolipoma (benign), non-tumor part', 'histology: Adenomyomatous hyperplasia of gallbladder (benign), non-tumor part', 'histology: Focal nodular hyperplasia of liver (benign), non-tumor part', 'histology: Cholangiocarcinoma', 'histology: Cholangiocarcinoma (less than 40 generations)', 'histology: Hepatocellular carcinoma', 'histology: Inflammatory pseudotumor (benign)', 'histology: Angiomyolipoma (benign)', 'histology: Adenomyomatous hyperplasia of gallbladder (benign)', 'histology: Focal nodular hyperplasia of liver (benign)'], 1: ['age: 63', 'age: 34', 'age: 73', 'age: 76', 'age: 71', 'age: 68', 'age: 39', 'age: 31', 'age: 48', 'age: 66', 'age: 62', 'age: 75', 'age: 65', 'age: 55'], 2: ['Sex: M', 'Sex: F'], 3: ['molecule: miRNA']}\n" ] } ], "source": [ "from tools.preprocess import *\n", "import os\n", "\n", "# 1. First inspect the directory contents to identify what files are available\n", "print(\"Available files in the directory:\")\n", "files = os.listdir(in_cohort_dir)\n", "print(files)\n", "\n", "# Since there's only one file, we'll use it for both SOFT and matrix data\n", "if len(files) > 0:\n", " matrix_file = os.path.join(in_cohort_dir, files[0])\n", " soft_file = matrix_file # Same file serves both purposes\n", " \n", " # 2. 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", " background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n", "\n", " # 3. Obtain the sample characteristics dictionary from the clinical dataframe\n", " sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n", "\n", " # 4. Explicitly print out all the background information and the sample characteristics dictionary\n", " print(\"\\nBackground Information:\")\n", " print(background_info)\n", " print(\"\\nSample Characteristics Dictionary:\")\n", " print(sample_characteristics_dict)\n", "else:\n", " raise FileNotFoundError(\"No files found in the directory\")\n" ] }, { "cell_type": "markdown", "id": "d4be7567", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "a6803f7a", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:30:04.226315Z", "iopub.status.busy": "2025-03-25T07:30:04.226205Z", "iopub.status.idle": "2025-03-25T07:30:04.242371Z", "shell.execute_reply": "2025-03-25T07:30:04.242018Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Preview of extracted clinical features:\n", "{'GSM1': [1.0, 63.0, 1.0], 'GSM2': [1.0, 34.0, 0.0], 'GSM3': [0.0, 73.0, nan], 'GSM4': [0.0, 76.0, nan], 'GSM5': [1.0, 71.0, nan], 'GSM6': [0.0, 68.0, nan], 'GSM7': [0.0, 39.0, nan], 'GSM8': [0.0, 31.0, nan], 'GSM9': [0.0, 48.0, nan], 'GSM10': [0.0, 66.0, nan], 'GSM11': [0.0, 62.0, nan], 'GSM12': [0.0, 75.0, nan], 'GSM13': [0.0, 65.0, nan], 'GSM14': [0.0, 55.0, nan], 'GSM15': [1.0, nan, nan], 'GSM16': [1.0, nan, nan], 'GSM17': [1.0, nan, nan], 'GSM18': [0.0, nan, nan], 'GSM19': [0.0, nan, nan], 'GSM20': [0.0, nan, nan], 'GSM21': [0.0, nan, nan]}\n", "Clinical data saved to: ../../output/preprocess/Liver_Cancer/clinical_data/GSE209875.csv\n" ] } ], "source": [ "# 1. Gene Expression Data Availability\n", "# Based on the series title and sample characteristics, while this dataset contains mRNA data,\n", "# the molecule field indicates this specific matrix file only contains miRNA data\n", "is_gene_available = False\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "\n", "# For trait: The histology field (key 0) contains information about liver cancer types\n", "trait_row = 0\n", "\n", "# For age: Available in key 1\n", "age_row = 1\n", "\n", "# For gender: Available in key 2\n", "gender_row = 2\n", "\n", "# 2.2 Data Type Conversion Functions\n", "\n", "def convert_trait(value):\n", " \"\"\"Convert histology data to binary trait indicating liver cancer (1) vs benign/non-tumor (0)\"\"\"\n", " if not isinstance(value, str):\n", " return None\n", " \n", " # Extract the value after the colon\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Categorize based on the histology description\n", " if 'benign' in value.lower() or 'non-tumor part' in value.lower():\n", " return 0 # Benign condition or non-tumor tissue\n", " elif 'carcinoma' in value.lower() and 'tumor part' in value.lower():\n", " return 1 # Malignant tumor tissue\n", " elif 'carcinoma' in value.lower() and 'tumor part' not in value.lower() and 'non-tumor part' not in value.lower():\n", " return 1 # Just specifying carcinoma without tissue part\n", " else:\n", " return None # Unknown or unclear classification\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age data to continuous value\"\"\"\n", " if not isinstance(value, str):\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:\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender data to binary (0=female, 1=male)\"\"\"\n", " if not isinstance(value, str):\n", " return None\n", " \n", " # Extract the value after the colon\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " if value.upper() == 'F':\n", " return 0\n", " elif value.upper() == 'M':\n", " return 1\n", " else:\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Trait data is available since trait_row is not None\n", "is_trait_available = trait_row is not None\n", "\n", "# Initial filtering based on gene and trait availability\n", "validate_and_save_cohort_info(\n", " is_final=False,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=is_gene_available,\n", " is_trait_available=is_trait_available\n", ")\n", "\n", "# 4. Clinical Feature Extraction\n", "# Since trait_row is not None, we need to extract clinical features\n", "if trait_row is not None:\n", " # Create a proper DataFrame from the sample characteristics data\n", " # We need to create a DataFrame where each column is a sample and rows are characteristics\n", " sample_chars = {\n", " 0: ['histology: Cholangiocarcinoma, tumor part', 'histology: Cholangiocarcinoma (less than 40 generations), tumor part', 'histology: Cholangiocarcinoma, non-tumor part', 'histology: Cholangiocarcinoma (less than 40 generations), non-tumor part', 'histology: Hepatocellular carcinoma, tumor part', 'histology: Hepatocellular carcinoma, non-tumor part', 'histology: Inflammatory pseudotumor (benign), tumor part', 'histology: Angiomyolipoma (benign), tumor part', 'histology: Adenomyomatous hyperplasia of gallbladder (benign), tumor part', 'histology: Focal nodular hyperplasia of liver (benign), tumor part', 'histology: Inflammatory pseudotumor (benign), non-tumor part', 'histology: Angiomyolipoma (benign), non-tumor part', 'histology: Adenomyomatous hyperplasia of gallbladder (benign), non-tumor part', 'histology: Focal nodular hyperplasia of liver (benign), non-tumor part', 'histology: Cholangiocarcinoma', 'histology: Cholangiocarcinoma (less than 40 generations)', 'histology: Hepatocellular carcinoma', 'histology: Inflammatory pseudotumor (benign)', 'histology: Angiomyolipoma (benign)', 'histology: Adenomyomatous hyperplasia of gallbladder (benign)', 'histology: Focal nodular hyperplasia of liver (benign)'],\n", " 1: ['age: 63', 'age: 34', 'age: 73', 'age: 76', 'age: 71', 'age: 68', 'age: 39', 'age: 31', 'age: 48', 'age: 66', 'age: 62', 'age: 75', 'age: 65', 'age: 55'],\n", " 2: ['Sex: M', 'Sex: F'],\n", " 3: ['molecule: miRNA']\n", " }\n", " \n", " # Create a DataFrame in the expected format (characteristics as rows) with sample IDs as columns\n", " # For simplicity, we'll create a mock format with sample IDs as GSM1, GSM2, etc.\n", " # First, determine how many samples we need (maximum number needed for any characteristic)\n", " max_samples = max(len(values) for values in sample_chars.values())\n", " \n", " # Create a DataFrame with rows for each characteristic type\n", " clinical_data = pd.DataFrame(index=[0, 1, 2, 3])\n", " \n", " # Add columns for each sample\n", " for i in range(max_samples):\n", " sample_id = f\"GSM{i+1}\"\n", " sample_data = {}\n", " \n", " # For each characteristic type, get the value if available\n", " for char_type in sample_chars:\n", " if i < len(sample_chars[char_type]):\n", " sample_data[char_type] = sample_chars[char_type][i]\n", " else:\n", " sample_data[char_type] = None\n", " \n", " clinical_data[sample_id] = pd.Series(sample_data)\n", " \n", " # Extract clinical features using the provided 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 extracted data\n", " preview = preview_df(selected_clinical_df)\n", " print(\"Preview of extracted clinical features:\")\n", " print(preview)\n", " \n", " # Save the extracted clinical data\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": "78d98a82", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "77fe9168", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:30:04.243349Z", "iopub.status.busy": "2025-03-25T07:30:04.243243Z", "iopub.status.idle": "2025-03-25T07:30:04.246206Z", "shell.execute_reply": "2025-03-25T07:30:04.245867Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "This dataset does not contain gene expression data (only miRNA data).\n", "Skipping gene expression data extraction.\n" ] } ], "source": [ "# Check if the dataset contains gene expression data based on previous assessment\n", "if not is_gene_available:\n", " print(\"This dataset does not contain gene expression data (only miRNA data).\")\n", " print(\"Skipping gene expression data extraction.\")\n", "else:\n", " # Get the matrix file directly rather than using geo_get_relevant_filepaths\n", " files = os.listdir(in_cohort_dir)\n", " if len(files) > 0:\n", " matrix_file = os.path.join(in_cohort_dir, files[0])\n", " print(f\"Matrix file found: {matrix_file}\")\n", " \n", " try:\n", " # Extract gene data\n", " gene_data = get_genetic_data(matrix_file)\n", " print(f\"Gene data shape: {gene_data.shape}\")\n", " \n", " # Print the first 20 gene/probe identifiers\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", " else:\n", " print(\"No files found in the input directory.\")" ] } ], "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 }