{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "fa18649a", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:10:01.642928Z", "iopub.status.busy": "2025-03-25T04:10:01.642479Z", "iopub.status.idle": "2025-03-25T04:10:01.826652Z", "shell.execute_reply": "2025-03-25T04:10:01.826302Z" } }, "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 = \"Thyroid_Cancer\"\n", "cohort = \"GSE104006\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Thyroid_Cancer\"\n", "in_cohort_dir = \"../../input/GEO/Thyroid_Cancer/GSE104006\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Thyroid_Cancer/GSE104006.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Thyroid_Cancer/gene_data/GSE104006.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Thyroid_Cancer/clinical_data/GSE104006.csv\"\n", "json_path = \"../../output/preprocess/Thyroid_Cancer/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "7fdb4331", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "0abfbf9b", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:10:01.828088Z", "iopub.status.busy": "2025-03-25T04:10:01.827931Z", "iopub.status.idle": "2025-03-25T04:10:01.926231Z", "shell.execute_reply": "2025-03-25T04:10:01.925896Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"miRNA and gene expression profiling in human thyroid carcinomas and non-neoplastic thyroids\"\n", "!Series_summary\t\"This SuperSeries is composed of the SubSeries listed below.\"\n", "!Series_overall_design\t\"Refer to individual Series\"\n", "Sample Characteristics Dictionary:\n", "{0: ['disease: Thyroid_carcinoma', 'disease: Non-neoplastic_thyroid'], 1: ['histology: PDTC', 'histology: PDTC+ATC', 'histology: PTC', 'histology: Non-neoplastic_thyroid', 'histology: PDTC+PTC', 'histology: PTC_lymph_node_metastasis', 'histology: PTC+PDTC'], 2: ['age: 74', 'age: 67', 'age: 72', 'age: 38', 'age: 50', 'age: 41', 'age: 51', 'age: 73', 'age: 52', 'age: 48', 'age: 59', 'age: 58', 'age: 39', 'age: 37', 'age: 33', 'age: 36', 'age: 70', 'age: 26', 'age: 46', 'age: 57', 'age: 44', 'age: 35', 'age: 42', 'age: 61', 'age: 49'], 3: ['Sex: M', 'Sex: F']}\n" ] } ], "source": [ "from tools.preprocess import *\n", "# 1. Identify the paths to the SOFT file and the matrix file\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\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(\"Background Information:\")\n", "print(background_info)\n", "print(\"Sample Characteristics Dictionary:\")\n", "print(sample_characteristics_dict)\n" ] }, { "cell_type": "markdown", "id": "04766a5e", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "a7d7ff09", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:10:01.927465Z", "iopub.status.busy": "2025-03-25T04:10:01.927348Z", "iopub.status.idle": "2025-03-25T04:10:01.933357Z", "shell.execute_reply": "2025-03-25T04:10:01.933065Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Clinical data file not found at ../../input/GEO/Thyroid_Cancer/GSE104006/clinical_data.csv\n", "Skipping clinical feature extraction.\n" ] } ], "source": [ "import pandas as pd\n", "import os\n", "import numpy as np\n", "from typing import Callable, Optional, Dict, Any\n", "import json\n", "\n", "# 1. Gene Expression Data Availability\n", "# Based on the title and summary, this dataset appears to contain gene expression data\n", "is_gene_available = True\n", "\n", "# 2.1 Data Availability\n", "# For trait, key 0 contains disease status (Thyroid_carcinoma vs Non-neoplastic_thyroid)\n", "trait_row = 0\n", "# For age, key 2 contains age information\n", "age_row = 2\n", "# For gender, key 3 contains sex information\n", "gender_row = 3\n", "\n", "# 2.2 Data Type Conversion\n", "def convert_trait(value):\n", " \"\"\"Convert trait value to binary format: 1 for Thyroid_carcinoma, 0 for Non-neoplastic_thyroid.\"\"\"\n", " if isinstance(value, str):\n", " # Extract the value after the colon\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " if value.lower() == 'thyroid_carcinoma':\n", " return 1\n", " elif value.lower() == 'non-neoplastic_thyroid':\n", " return 0\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age value to continuous format.\"\"\"\n", " if isinstance(value, str):\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", " pass\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender value to binary format: 1 for male, 0 for female.\"\"\"\n", " if isinstance(value, str):\n", " # Extract the value after the colon\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " if value.upper() == 'M':\n", " return 1\n", " elif value.upper() == 'F':\n", " return 0\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", "# For this step, we'll check if clinical data exists before processing\n", "if trait_row is not None:\n", " clinical_file_path = os.path.join(in_cohort_dir, \"clinical_data.csv\")\n", " \n", " if os.path.exists(clinical_file_path):\n", " try:\n", " # Load the clinical data\n", " clinical_data = pd.read_csv(clinical_file_path)\n", " \n", " # Use the function to extract clinical features\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 dataframe\n", " preview = preview_df(selected_clinical_df)\n", " print(\"Preview of selected clinical features:\")\n", " print(preview)\n", " \n", " # Save the processed 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", " except Exception as e:\n", " print(f\"Error processing clinical data: {e}\")\n", " else:\n", " print(f\"Clinical data file not found at {clinical_file_path}\")\n", " print(\"Skipping clinical feature extraction.\")\n", "else:\n", " print(\"No trait data available, skipping clinical feature extraction.\")\n" ] }, { "cell_type": "markdown", "id": "8763f82e", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "f26ebc34", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:10:01.934436Z", "iopub.status.busy": "2025-03-25T04:10:01.934328Z", "iopub.status.idle": "2025-03-25T04:10:02.069076Z", "shell.execute_reply": "2025-03-25T04:10:02.068723Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "SOFT file: ../../input/GEO/Thyroid_Cancer/GSE104006/GSE104006_family.soft.gz\n", "Matrix file: ../../input/GEO/Thyroid_Cancer/GSE104006/GSE104006-GPL14951_series_matrix.txt.gz\n", "Found the matrix table marker in the file.\n", "Gene data shape: (29377, 34)\n", "First 20 gene/probe identifiers:\n", "['ILMN_1343291', 'ILMN_1651209', 'ILMN_1651228', 'ILMN_1651229', 'ILMN_1651235', 'ILMN_1651236', 'ILMN_1651237', 'ILMN_1651238', 'ILMN_1651254', 'ILMN_1651260', 'ILMN_1651262', 'ILMN_1651268', 'ILMN_1651278', 'ILMN_1651282', 'ILMN_1651285', 'ILMN_1651286', 'ILMN_1651292', 'ILMN_1651303', 'ILMN_1651309', 'ILMN_1651315']\n" ] } ], "source": [ "# 1. Identify the paths to the SOFT file and the matrix file\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "print(f\"SOFT file: {soft_file}\")\n", "print(f\"Matrix file: {matrix_file}\")\n", "\n", "# Set gene availability flag\n", "is_gene_available = True # Initially assume gene data is available\n", "\n", "# First check if the matrix file contains the expected marker\n", "found_marker = False\n", "try:\n", " with gzip.open(matrix_file, 'rt') as file:\n", " for line in file:\n", " if \"!series_matrix_table_begin\" in line:\n", " found_marker = True\n", " break\n", " \n", " if found_marker:\n", " print(\"Found the matrix table marker in the file.\")\n", " else:\n", " print(\"Warning: Could not find '!series_matrix_table_begin' marker in the file.\")\n", " \n", " # Try to extract gene data from the matrix file\n", " gene_data = get_genetic_data(matrix_file)\n", " \n", " if gene_data.shape[0] == 0:\n", " print(\"Warning: Extracted gene data has 0 rows.\")\n", " is_gene_available = False\n", " else:\n", " print(f\"Gene data shape: {gene_data.shape}\")\n", " # Print the first 20 gene/probe identifiers\n", " print(\"First 20 gene/probe identifiers:\")\n", " print(gene_data.index[:20].tolist())\n", " \n", "except Exception as e:\n", " print(f\"Error extracting gene data: {e}\")\n", " is_gene_available = False\n", " \n", " # Try to diagnose the file format\n", " print(\"Examining file content to diagnose the issue:\")\n", " try:\n", " with gzip.open(matrix_file, 'rt') as file:\n", " for i, line in enumerate(file):\n", " if i < 10: # Print first 10 lines to diagnose\n", " print(f\"Line {i}: {line.strip()[:100]}...\") # Print first 100 chars of each line\n", " else:\n", " break\n", " except Exception as e2:\n", " print(f\"Error examining file: {e2}\")\n", "\n", "if not is_gene_available:\n", " print(\"Gene expression data could not be successfully extracted from this dataset.\")\n" ] }, { "cell_type": "markdown", "id": "41a2a49f", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "de37464e", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:10:02.070371Z", "iopub.status.busy": "2025-03-25T04:10:02.070251Z", "iopub.status.idle": "2025-03-25T04:10:02.072374Z", "shell.execute_reply": "2025-03-25T04:10:02.072079Z" } }, "outputs": [], "source": [ "# Reviewing the gene identifiers from the output\n", "# These identifiers like 'hsa-let-7a-3p', 'hsa-let-7b-5p' appear to be microRNA identifiers\n", "# The 'hsa-' prefix indicates human (Homo sapiens) microRNAs\n", "# These are standard microRNA nomenclature, not gene symbols like BRCA1 or TP53\n", "# They don't require mapping to gene symbols as they're already in a standard format\n", "\n", "requires_gene_mapping = False" ] } ], "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 }