{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "64f51cb0", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:08:41.983736Z", "iopub.status.busy": "2025-03-25T04:08:41.983620Z", "iopub.status.idle": "2025-03-25T04:08:42.152772Z", "shell.execute_reply": "2025-03-25T04:08:42.152308Z" } }, "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 = \"Testicular_Cancer\"\n", "cohort = \"GSE62523\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Testicular_Cancer\"\n", "in_cohort_dir = \"../../input/GEO/Testicular_Cancer/GSE62523\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Testicular_Cancer/GSE62523.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Testicular_Cancer/gene_data/GSE62523.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Testicular_Cancer/clinical_data/GSE62523.csv\"\n", "json_path = \"../../output/preprocess/Testicular_Cancer/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "e3627632", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "a1c727cf", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:08:42.154329Z", "iopub.status.busy": "2025-03-25T04:08:42.154180Z", "iopub.status.idle": "2025-03-25T04:08:42.287656Z", "shell.execute_reply": "2025-03-25T04:08:42.287170Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Files in the cohort directory:\n", "['GSE62523_family.soft.gz', 'GSE62523_series_matrix.txt.gz']\n", "Identified SOFT files: ['GSE62523_family.soft.gz']\n", "Identified matrix files: ['GSE62523_series_matrix.txt.gz']\n", "\n", "Background Information:\n", "!Series_title\t\"Gene expression profiles of HMEC-1 after exposure to the chemotherapeutic drugs bleomycin and cisplatin with untreated samples as control\"\n", "!Series_summary\t\"Chemotherapy-related endothelial damage contributes to the early development of cardiovascular morbidity in testicular cancer patients. We aimed to identify relevant mechanisms of and search for candidate biomarkers for this endothelial damage.\"\n", "!Series_summary\t\"Human micro-vascular endothelial cells (HMEC-1) were exposed to bleomycin or cisplatin with untreated samples as control. 18k cDNA microarrays were used. Gene expression differences were analysed at single gene level and in gene sets clustered in biological pathways and validated by qRT-PCR. Protein levels of a candidate biomarker were measured in testicular cancer patient plasma before, during and after bleomycin-etoposide-cisplatin chemotherapy, and related to endothelial damage biomarkers (von Willebrand Factor (vWF), high-sensitivity C-Reactive Protein (hsCRP)).\"\n", "!Series_summary\t\"Microarray data identified several genes with highly differential expression; e.g. Growth Differentiation Factor 15 (GDF-15), Activating Transcription Factor 3 (ATF3) and Amphiregulin (AREG). Pathway analysis revealed strong associations with ‘p53’ and ‘Diabetes Mellitus’ gene sets. Based on known function, we measured GDF-15 protein levels in 41 testicular patients during clinical follow-up. Pre-chemotherapy GDF-15 levels equalled controls. Throughout chemotherapy GDF-15, vWF and hsCRP levels increased, and were correlated at different time-points.\"\n", "!Series_summary\t\"An unbiased approach in a preclinical model revealed genes related to chemotherapy-induced endothelial damage, like GDF-15. The increases in plasma GDF-15 levels in testicular cancer patients during chemotherapy and its association with vWF and hsCRP suggest that GDF-15 is a potentially useful biomarker related to endothelial damage.\"\n", "!Series_overall_design\t\"In an acute-exposure setting, HMEC-1 were left untreated as controls or were treated with 0.3 (IC50 (concentration inhibiting cell survival by 50%)) or 1.5 ug/mL (IC90) bleomycin and 2.6 (IC50) and 12.9 uM (IC90) cisplatin for 6, 24 and 48 hours. In a chronic-exposure setting, lower doses were administrated (IC10; bleomycin 0.06 ug/mL or cisplatin 0.52 uM) two times a week; cells were collected for analysis at day 30. Administration of cisplatin had to be withheld at the 7th administration because of considerable cell dead, but was continued at full dose thereafter. Bleomycin could be administrated without disruption. Total RNA was isolated from HMEC-1 and pooled for each time point and drug concentration from 2 independent experiments.\"\n", "\n", "Sample Characteristics Dictionary:\n", "{0: ['cell line: HMEC-1'], 1: ['cell type: human microvascular endothelial cell line']}\n" ] } ], "source": [ "# 1. Let's first list the directory contents to understand what files are available\n", "import os\n", "\n", "print(\"Files in the cohort directory:\")\n", "files = os.listdir(in_cohort_dir)\n", "print(files)\n", "\n", "# Adapt file identification to handle different naming patterns\n", "soft_files = [f for f in files if 'soft' in f.lower() or '.soft' in f.lower() or '_soft' in f.lower()]\n", "matrix_files = [f for f in files if 'matrix' in f.lower() or '.matrix' in f.lower() or '_matrix' in f.lower()]\n", "\n", "# If no files with these patterns are found, look for alternative file types\n", "if not soft_files:\n", " soft_files = [f for f in files if f.endswith('.txt') or f.endswith('.gz')]\n", "if not matrix_files:\n", " matrix_files = [f for f in files if f.endswith('.txt') or f.endswith('.gz')]\n", "\n", "print(\"Identified SOFT files:\", soft_files)\n", "print(\"Identified matrix files:\", matrix_files)\n", "\n", "# Use the first files found, if any\n", "if len(soft_files) > 0 and len(matrix_files) > 0:\n", " soft_file = os.path.join(in_cohort_dir, soft_files[0])\n", " matrix_file = os.path.join(in_cohort_dir, matrix_files[0])\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", " print(\"No appropriate files found in the directory.\")\n" ] }, { "cell_type": "markdown", "id": "52196f24", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "9e361e9c", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:08:42.288902Z", "iopub.status.busy": "2025-03-25T04:08:42.288786Z", "iopub.status.idle": "2025-03-25T04:08:42.295933Z", "shell.execute_reply": "2025-03-25T04:08:42.295557Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "A new JSON file was created at: ../../output/preprocess/Testicular_Cancer/cohort_info.json\n" ] }, { "data": { "text/plain": [ "False" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Step 1: Check gene expression data availability\n", "# Based on the background information, this seems to be a gene expression dataset of HMEC-1 cell line\n", "# The description mentions 18k cDNA microarrays were used\n", "is_gene_available = True\n", "\n", "# Step 2: Analyze variable availability\n", "\n", "# 2.1 Data Availability\n", "# The sample characteristics show this dataset is about HMEC-1 cell line exposed to chemotherapeutic drugs\n", "# Looking at the characteristics, there's no specific information about testicular cancer patients, age, or gender\n", "# This appears to be a cell line study, not a patient cohort with trait, age, or gender information\n", "\n", "# For Testicular Cancer trait: Not directly available in cell line data\n", "trait_row = None\n", "\n", "# For Age: Not applicable for cell line data\n", "age_row = None \n", "\n", "# For Gender: Not applicable for cell line data\n", "gender_row = None\n", "\n", "# 2.2 Data Type Conversion Functions\n", "# Even though we won't use these functions since we don't have the data,\n", "# we'll define them as required by the task structure\n", "\n", "def convert_trait(value):\n", " \"\"\"Convert trait value to binary format.\n", " Since this is a cell line study, this function won't be used.\"\"\"\n", " if value is None:\n", " return None\n", " # Extract value after colon if present\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " return None # Not applicable for this dataset\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age value to continuous format.\n", " Since this is a cell line study, this function won't be used.\"\"\"\n", " if value is None:\n", " return None\n", " # Extract value after colon if present\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " return None # Not applicable for this dataset\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender value to binary format.\n", " Since this is a cell line study, this function won't be used.\"\"\"\n", " if value is None:\n", " return None\n", " # Extract value after colon if present\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " return None # Not applicable for this dataset\n", "\n", "# Step 3: Save Metadata\n", "# The dataset doesn't contain human trait data as it's a cell line study\n", "is_trait_available = trait_row is not None\n", "\n", "# Perform initial validation and save the cohort info\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", "# Step 4: Clinical Feature Extraction\n", "# We skip this step since trait_row is None (clinical data not available for this type of study)\n" ] }, { "cell_type": "markdown", "id": "ad9b6b63", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "3a5d7ae0", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:08:42.296992Z", "iopub.status.busy": "2025-03-25T04:08:42.296884Z", "iopub.status.idle": "2025-03-25T04:08:42.536551Z", "shell.execute_reply": "2025-03-25T04:08:42.536012Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "First 20 gene/probe identifiers:\n", "Index(['1.1.1.1', '1.1.1.10', '1.1.1.11', '1.1.1.12', '1.1.1.13', '1.1.1.14',\n", " '1.1.1.15', '1.1.1.16', '1.1.1.17', '1.1.1.18', '1.1.1.19', '1.1.1.2',\n", " '1.1.1.20', '1.1.1.21', '1.1.1.22', '1.1.1.23', '1.1.1.3', '1.1.1.4',\n", " '1.1.1.5', '1.1.1.6'],\n", " dtype='object', name='ID')\n", "\n", "Gene expression data shape: (25392, 104)\n" ] } ], "source": [ "# Use the helper function to get the proper file paths\n", "soft_file_path, matrix_file_path = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# Extract gene expression data\n", "try:\n", " gene_data = get_genetic_data(matrix_file_path)\n", " \n", " # Print the first 20 row IDs (gene or probe identifiers)\n", " print(\"First 20 gene/probe identifiers:\")\n", " print(gene_data.index[:20])\n", " \n", " # Print shape to understand the dataset dimensions\n", " print(f\"\\nGene expression data shape: {gene_data.shape}\")\n", " \n", "except Exception as e:\n", " print(f\"Error extracting gene data: {e}\")\n" ] }, { "cell_type": "markdown", "id": "495a3047", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "de1ecd3d", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:08:42.538083Z", "iopub.status.busy": "2025-03-25T04:08:42.537927Z", "iopub.status.idle": "2025-03-25T04:08:42.540575Z", "shell.execute_reply": "2025-03-25T04:08:42.540136Z" } }, "outputs": [], "source": [ "# Looking at the gene identifiers, these appear to be probe identifiers and not standard human gene symbols\n", "# They follow a pattern like \"1.1.1.1\", \"1.1.1.2\", etc., which is not consistent with standard gene symbols\n", "# Standard human gene symbols are typically alphabetic (e.g., TP53, BRCA1, MYC)\n", "# These identifiers will need to be mapped to standard gene symbols\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "4d230f34", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "f699eabb", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:08:42.541890Z", "iopub.status.busy": "2025-03-25T04:08:42.541786Z", "iopub.status.idle": "2025-03-25T04:08:45.640994Z", "shell.execute_reply": "2025-03-25T04:08:45.640436Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene annotation preview:\n", "{'ID': ['1.1.1.1', '1.1.1.2', '1.1.1.3', '1.1.1.4', '1.1.1.5'], 'Meta Row': ['1', '1', '1', '1', '1'], 'Meta Column': [1.0, 1.0, 1.0, 1.0, 1.0], 'Row': [1.0, 1.0, 1.0, 1.0, 1.0], 'Column': [1.0, 2.0, 3.0, 4.0, 5.0], 'Gene ID': ['c_Cy-3 landmark', 'c_Cy-3 landmark', 'c_Cy-5 landmark', 'AK056492', 'AK057091'], 'GB_ACC': [nan, nan, nan, 'AK056492', 'AK057091'], 'Gene symbol': [nan, nan, nan, 'ZNF827', 'FAM120B'], 'SPOT_ID': ['c_Cy-3 landmark', 'c_Cy-3 landmark', 'c_Cy-5 landmark', nan, nan]}\n" ] } ], "source": [ "# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n", "try:\n", " # Use the correct variable name from previous steps\n", " gene_annotation = get_gene_annotation(soft_file_path)\n", " \n", " # 2. Preview the gene annotation dataframe\n", " print(\"Gene annotation preview:\")\n", " print(preview_df(gene_annotation))\n", " \n", "except UnicodeDecodeError as e:\n", " print(f\"Unicode decoding error: {e}\")\n", " print(\"Trying alternative approach...\")\n", " \n", " # Read the file with Latin-1 encoding which is more permissive\n", " import gzip\n", " import pandas as pd\n", " \n", " # Manually read the file line by line with error handling\n", " data_lines = []\n", " with gzip.open(soft_file_path, 'rb') as f:\n", " for line in f:\n", " # Skip lines starting with prefixes we want to filter out\n", " line_str = line.decode('latin-1')\n", " if not line_str.startswith('^') and not line_str.startswith('!') and not line_str.startswith('#'):\n", " data_lines.append(line_str)\n", " \n", " # Create dataframe from collected lines\n", " if data_lines:\n", " gene_data_str = '\\n'.join(data_lines)\n", " gene_annotation = pd.read_csv(pd.io.common.StringIO(gene_data_str), sep='\\t', low_memory=False)\n", " print(\"Gene annotation preview (alternative method):\")\n", " print(preview_df(gene_annotation))\n", " else:\n", " print(\"No valid gene annotation data found after filtering.\")\n", " gene_annotation = pd.DataFrame()\n", " \n", "except Exception as e:\n", " print(f\"Error extracting gene annotation data: {e}\")\n", " gene_annotation = pd.DataFrame()\n" ] }, { "cell_type": "markdown", "id": "835a3517", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "ffdbc28a", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:08:45.642312Z", "iopub.status.busy": "2025-03-25T04:08:45.642185Z", "iopub.status.idle": "2025-03-25T04:08:45.859742Z", "shell.execute_reply": "2025-03-25T04:08:45.859196Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene mapping preview:\n", " ID Gene\n", "3 1.1.1.4 ZNF827\n", "4 1.1.1.5 FAM120B\n", "5 1.1.1.6 ZNF655\n", "6 1.1.1.7 KRAS\n", "7 1.1.1.8 RPP14\n", "Mapping data shape: (18201, 2)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "After mapping to gene symbols:\n", "Gene expression data shape: (15399, 104)\n", "First 10 genes:\n", "Index(['A1BG', 'A1CF', 'A2BP1', 'A2M', 'A2ML1', 'A4GALT', 'A4GNT', 'AAAS',\n", " 'AACS', 'AADAC'],\n", " dtype='object', name='Gene')\n" ] } ], "source": [ "# 1. Identify which columns to use for mapping\n", "# From the gene annotation preview, we need to use:\n", "# - 'ID' column as the gene identifier that matches the index in gene_data\n", "# - 'Gene symbol' column for the human gene symbols\n", "\n", "# 2. Create a mapping dataframe with the relevant columns\n", "prob_col = 'ID'\n", "gene_col = 'Gene symbol'\n", "mapping_data = get_gene_mapping(gene_annotation, prob_col, gene_col)\n", "\n", "# Look at the mapping data \n", "print(\"Gene mapping preview:\")\n", "print(mapping_data.head())\n", "print(f\"Mapping data shape: {mapping_data.shape}\")\n", "\n", "# 3. Apply the gene mapping to convert probe-level measurements to gene expression data\n", "gene_data = apply_gene_mapping(gene_data, mapping_data)\n", "\n", "# Print information about the resulting gene expression data\n", "print(\"\\nAfter mapping to gene symbols:\")\n", "print(f\"Gene expression data shape: {gene_data.shape}\")\n", "print(\"First 10 genes:\")\n", "print(gene_data.index[:10])\n" ] }, { "cell_type": "markdown", "id": "baa599de", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "f691ef6c", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:08:45.861119Z", "iopub.status.busy": "2025-03-25T04:08:45.860983Z", "iopub.status.idle": "2025-03-25T04:08:46.738481Z", "shell.execute_reply": "2025-03-25T04:08:46.737804Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data shape: (15073, 104)\n", "First few normalized gene symbols: ['A1BG', 'A1CF', 'A2M', 'A2ML1', 'A4GALT', 'A4GNT', 'AAAS', 'AACS', 'AADAC', 'AADAT']\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data saved to ../../output/preprocess/Testicular_Cancer/gene_data/GSE62523.csv\n", "Clinical data (empty) saved to ../../output/preprocess/Testicular_Cancer/clinical_data/GSE62523.csv\n", "Data quality check result: Not usable\n", "Dataset is not usable for trait association study as it doesn't contain trait data.\n" ] } ], "source": [ "# 1. Normalize gene symbols in the obtained gene expression data using the provided function\n", "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"Normalized gene data shape: {normalized_gene_data.shape}\")\n", "print(f\"First few normalized gene symbols: {list(normalized_gene_data.index[:10])}\")\n", "\n", "# Save the normalized gene data to CSV\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 data saved to {out_gene_data_file}\")\n", "\n", "# Since previous steps determined that trait_row is None and is_trait_available is False,\n", "# we should use is_final=False for the validation (which doesn't require is_biased)\n", "# Conduct quality check with correct trait availability (False)\n", "is_usable = validate_and_save_cohort_info(\n", " is_final=False, \n", " cohort=cohort, \n", " info_path=json_path, \n", " is_gene_available=True, \n", " is_trait_available=False # Correctly report that trait data is not available\n", ")\n", "\n", "# Create a minimal clinical dataframe for linking (note: this is empty in this case)\n", "clinical_df = pd.DataFrame()\n", "\n", "# Save empty clinical data for consistency\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 (empty) saved to {out_clinical_data_file}\")\n", "\n", "print(f\"Data quality check result: {'Usable' if is_usable else 'Not usable'}\")\n", "print(\"Dataset is not usable for trait association study as it doesn't contain trait data.\")" ] } ], "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 }