{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "3f60932d", "metadata": {}, "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 = \"Breast_Cancer\"\n", "cohort = \"GSE283522\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Breast_Cancer\"\n", "in_cohort_dir = \"../../input/GEO/Breast_Cancer/GSE283522\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Breast_Cancer/GSE283522.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Breast_Cancer/gene_data/GSE283522.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Breast_Cancer/clinical_data/GSE283522.csv\"\n", "json_path = \"../../output/preprocess/Breast_Cancer/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "e9505ea4", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": null, "id": "f4a5273b", "metadata": {}, "outputs": [], "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": "2b13b1c5", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "0f5284ae", "metadata": {}, "outputs": [], "source": [ "# 1. Gene Expression Data Availability\n", "# Based on the information in the background metadata, this dataset contains RNA-seq data\n", "# from FFPE breast tumors, indicating it contains gene expression data\n", "is_gene_available = True\n", "\n", "# 2.1 Data Availability\n", "# Trait (Breast Cancer) data is available\n", "# Row 6 contains 'sample category' which indicates whether the sample is invasive breast cancer \n", "# or other types like healthy, DCIS, etc.\n", "trait_row = 6\n", "\n", "# Age data is available in row 2\n", "age_row = 2\n", "\n", "# Gender/Sex data is available in row 5\n", "gender_row = 5\n", "\n", "# 2.2 Data Type Conversion\n", "def convert_trait(value):\n", " \"\"\"Convert trait data to binary (0: healthy/no cancer, 1: cancer).\"\"\"\n", " if pd.isna(value):\n", " return None\n", " \n", " # Split by colon and get the value part\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " # Map sample categories to binary values\n", " if \"invasive breast cancer\" in value:\n", " return 1\n", " elif \"true healthy\" in value or \"no tumor\" in value:\n", " return 0\n", " elif \"DCIS\" in value or \"LCIS\" in value or \"extra ROI\" in value:\n", " # These are precursor lesions or special cases, not considered invasive cancer\n", " return 0\n", " elif \"positive control\" in value:\n", " # Controls shouldn't be counted as cases\n", " return None\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age data to continuous values.\"\"\"\n", " if pd.isna(value):\n", " return None\n", " \n", " # Split by colon and get the value part\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " if \"not applicable\" in value or \"missing\" in value:\n", " return None\n", " \n", " # Age is given in ranges like \"55 - 59\"\n", " if \"-\" in value:\n", " # Extract the range and use the midpoint\n", " try:\n", " parts = value.replace(' ', '').split('-')\n", " lower = int(parts[0])\n", " upper = int(parts[1])\n", " return (lower + upper) / 2\n", " except:\n", " return None\n", " \n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender/sex data to binary (0: female, 1: male).\"\"\"\n", " if pd.isna(value):\n", " return None\n", " \n", " # Split by colon and get the value part\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " if \"not applicable\" in value or \"missing\" in value:\n", " return None\n", " \n", " if \"female\" in value.lower():\n", " return 0\n", " elif \"male\" in value.lower():\n", " return 1\n", " else:\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Conduct initial filtering on the usability of the dataset\n", "# trait_row is not None, so trait data is available\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", "# Since trait_row is not None, we need to extract clinical features\n", "# We need to create a DataFrame from the sample characteristics dictionary\n", "# The sample characteristics are the values provided in the previous output\n", "\n", "# Create a dictionary to store the sample characteristics for each row\n", "sample_chars = {}\n", "for row_idx, values in Sample_Characteristics_Dictionary.items():\n", " sample_chars[row_idx] = values\n", "\n", "# Convert the dictionary to a DataFrame\n", "clinical_data = pd.DataFrame(sample_chars)\n", "\n", "# Now extract the 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 selected clinical features\n", "preview = preview_df(selected_clinical_df)\n", "print(\"Preview of clinical features:\")\n", "print(preview)\n", "\n", "# Save the clinical data to a CSV file\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": "d2aa5260", "metadata": {}, "source": [ "### Step 3: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "ab227b7f", "metadata": {}, "outputs": [], "source": [ "import os\n", "import pandas as pd\n", "import json\n", "import gzip\n", "import re\n", "from typing import Callable, Optional\n", "\n", "# Check what files are available in the cohort directory\n", "cohort_files = os.listdir(in_cohort_dir)\n", "print(f\"Files in cohort directory: {cohort_files}\")\n", "\n", "# Function to parse GEO series matrix file\n", "def parse_geo_series_matrix(file_path):\n", " with gzip.open(file_path, 'rt') as f:\n", " lines = f.readlines()\n", " \n", " # Extract sample characteristics\n", " characteristics_rows = {}\n", " sample_ids = []\n", " data_start = False\n", " \n", " for i, line in enumerate(lines):\n", " if line.startswith('!Sample_geo_accession'):\n", " sample_ids = line.strip().split('\\t')[1:]\n", " elif line.startswith('!Sample_characteristics_ch1'):\n", " parts = line.strip().split('\\t')\n", " header = parts[0]\n", " values = parts[1:]\n", " if len(values) > 0:\n", " row_idx = len(characteristics_rows)\n", " characteristics_rows[row_idx] = values\n", " elif line.startswith('!series_matrix_table_begin'):\n", " data_start = True\n", " data_start_line = i\n", " break\n", " \n", " # Create clinical dataframe\n", " clinical_df = pd.DataFrame(index=sample_ids)\n", " for row_idx, values in characteristics_rows.items():\n", " clinical_df[f'characteristic_{row_idx}'] = values\n", " \n", " # Check if there's gene expression data\n", " has_gene_data = data_start\n", " \n", " return clinical_df, has_gene_data\n", "\n", "# Parse the GEO series matrix file\n", "series_matrix_path = os.path.join(in_cohort_dir, \"GSE283522_series_matrix.txt.gz\")\n", "if os.path.exists(series_matrix_path):\n", " clinical_data, is_gene_available = parse_geo_series_matrix(series_matrix_path)\n", " print(f\"Clinical data shape: {clinical_data.shape}\")\n", " \n", " # Display unique values for each sample characteristic\n", " for i, col in enumerate(clinical_data.columns):\n", " unique_values = clinical_data[col].unique()\n", " print(f\"Row {i}, Column '{col}': {unique_values}\")\n", "else:\n", " print(f\"Series matrix file not found: {series_matrix_path}\")\n", " clinical_data = pd.DataFrame()\n", " is_gene_available = False\n", "\n", "# Identify and process clinical variables\n", "def convert_trait(value):\n", " if pd.isna(value):\n", " return None\n", " \n", " value = str(value).lower()\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Convert to binary: 1 for breast cancer, 0 for control/normal\n", " if any(term in value for term in ['cancer', 'tumor', 'malignant', 'carcinoma']):\n", " return 1\n", " elif any(term in value for term in ['normal', 'control', 'benign', 'healthy']):\n", " return 0\n", " return None\n", "\n", "def convert_age(value):\n", " if pd.isna(value):\n", " return None\n", " \n", " value = str(value)\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Try to extract age as a number\n", " age_match = re.search(r'(\\d+)', value)\n", " if age_match:\n", " return float(age_match.group(1))\n", " return None\n", "\n", "def convert_gender(value):\n", " if pd.isna(value):\n", " return None\n", " \n", " value = str(value).lower()\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " if value in ['female', 'f', 'woman']:\n", " return 0\n", " elif value in ['male', 'm', 'man']:\n", " return 1\n", " return None\n", "\n", "# Initialize row indices as None\n", "trait_row = None\n", "age_row = None\n", "gender_row = None\n", "\n", "# Look through the sample characteristics to find the appropriate rows\n", "if not clinical_data.empty:\n", " for i, col in enumerate(clinical_data.columns):\n", " col_values = clinical_data[col].astype(str).str.lower()\n", " \n", " # Check for trait-related information\n", " trait_terms = ['tissue', 'diagnosis', 'sample type', 'status', 'source', 'histology', 'disease']\n", " if any(term in col.lower() for term in trait_terms):\n", " # Check if values indicate cancer/normal distinction\n", " has_trait_terms = any(('cancer' in val or 'tumor' in val or 'normal' in val or \n", " 'control' in val or 'benign' in val or 'malignant' in val) \n", " for val in col_values)\n", " # Check if there's more than one unique value\n", " has_multiple_values = len(set([convert_trait(val) for val in col_values if convert_trait(val) is not None])) > 1\n", " \n", " if has_trait_terms and has_multiple_values:\n", " trait_row = i\n", " \n", " # Check for age information\n", " if 'age' in col.lower():\n", " # Check if there's more than one unique value after conversion\n", " ages = [convert_age(val) for val in col_values if convert_age(val) is not None]\n", " if len(ages) > 1 and len(set(ages)) > 1:\n", " age_row = i\n", " \n", " # Check for gender information\n", " if 'gender' in col.lower() or 'sex' in col.lower():\n", " # Check if there's more than one unique value after conversion\n", " genders = [convert_gender(val) for val in col_values if convert_gender(val) is not None]\n", " if len(genders) > 1 and len(set(genders)) > 1:\n", " gender_row = i\n", "\n", "# Save metadata - initial filtering\n", "is_trait_available = trait_row is not None\n", "validate_and_save_cohort_info(is_final=False, cohort=cohort, info_path=json_path, \n", " is_gene_available=is_gene_available, \n", " is_trait_available=is_trait_available)\n", "\n", "# Extract clinical features if trait data is available\n", "if is_trait_available:\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 if age_row is not None else None,\n", " gender_row=gender_row,\n", " convert_gender=convert_gender if gender_row is not None else None\n", " )\n", " \n", " # Preview the selected clinical features\n", " preview = preview_df(selected_clinical_df)\n", " print(f\"Preview of selected 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 data\n", " selected_clinical_df.to_csv(out_clinical_data_file)\n", " print(f\"Clinical data saved to: {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "04bf58c2", "metadata": {}, "source": [ "### Step 4: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "f36f952e", "metadata": {}, "outputs": [], "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.\")" ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 5 }