{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "acc01913", "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 = \"Osteoporosis\"\n", "cohort = \"GSE20881\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Osteoporosis\"\n", "in_cohort_dir = \"../../input/GEO/Osteoporosis/GSE20881\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Osteoporosis/GSE20881.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Osteoporosis/gene_data/GSE20881.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Osteoporosis/clinical_data/GSE20881.csv\"\n", "json_path = \"../../output/preprocess/Osteoporosis/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "db9e4270", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": null, "id": "03317b94", "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": "9906fc40", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "b8d97b11", "metadata": {}, "outputs": [], "source": [ "# 1. Examine if the dataset contains gene expression data\n", "# Looking at the background information, this appears to be a gene expression dataset\n", "# focusing on Crohn's disease, not osteoporosis\n", "is_gene_available = True\n", "\n", "# 2. Identify available clinical data and create conversion functions\n", "\n", "# 2.1 Trait (Osteoporosis) availability\n", "# This dataset is about Crohn's disease, not osteoporosis\n", "# Looking at the data, osteoporosis is only mentioned as a comorbidity in \"other illnesses\"\n", "# This is not appropriate for studying osteoporosis as a primary trait\n", "trait_row = None # Setting to None as this dataset doesn't focus on osteoporosis\n", "\n", "def convert_trait(value):\n", " \"\"\"Convert trait data to binary format.\"\"\"\n", " # Not applicable for this dataset\n", " return None\n", "\n", "# 2.2 Age availability - Has birth date information but not relevant for our trait\n", "age_row = None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert birth date to age.\"\"\"\n", " # Not applicable for our analysis\n", " return None\n", "\n", "# 2.3 Gender availability - No clear gender information in the data\n", "gender_row = None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender data to binary format.\"\"\"\n", " # No gender data available\n", " return None\n", "\n", "# 3. Save metadata\n", "is_trait_available = trait_row is not None\n", "result = 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", "# Skip this step since trait_row is None (no relevant clinical data for osteoporosis)\n", "if trait_row is not None:\n", " # This block won't execute because trait_row is None\n", " pass\n" ] }, { "cell_type": "markdown", "id": "e9bdcfe4", "metadata": {}, "source": [ "### Step 3: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "627a5d85", "metadata": {}, "outputs": [], "source": [ "I'll fix the code to properly explore the GEO dataset, identify clinical features, and extract/save the data according to the requirements.\n", "\n", "```python\n", "# Let's first examine the information we have from a previous step\n", "# Since we're working with GEO data, we need to check for common GEO file formats\n", "\n", "import pandas as pd\n", "import os\n", "import json\n", "import re\n", "from typing import Callable, Optional, Dict, Any\n", "\n", "# First, let's list all files in the input directory to understand what's available\n", "print(\"Files in the input directory:\")\n", "input_files = os.listdir(in_cohort_dir)\n", "print(input_files)\n", "\n", "# Check for common GEO file formats\n", "family_soft = None\n", "series_matrix = None\n", "clinical_data = None\n", "\n", "for file in input_files:\n", " if file.endswith('.soft') or 'family' in file.lower():\n", " family_soft = os.path.join(in_cohort_dir, file)\n", " elif 'series_matrix' in file.lower() or file.endswith('.txt'):\n", " series_matrix = os.path.join(in_cohort_dir, file)\n", " elif 'clinical' in file.lower() or 'sample' in file.lower() or 'characteristics' in file.lower():\n", " clinical_data = pd.read_csv(os.path.join(in_cohort_dir, file))\n", "\n", "# Try to load data from the identified files\n", "if clinical_data is not None:\n", " print(\"Clinical data found directly\")\n", "elif series_matrix is not None:\n", " print(f\"Found series matrix file: {series_matrix}\")\n", " # Read the first 100 lines to extract sample characteristics\n", " with open(series_matrix, 'r') as f:\n", " lines = [f.readline() for _ in range(100)]\n", " \n", " # Look for sample characteristics in the header\n", " sample_chars = []\n", " for line in lines:\n", " if line.startswith('!Sample_characteristics_ch1'):\n", " sample_chars.append(line.strip())\n", " \n", " # Create a dataframe from the sample characteristics\n", " if sample_chars:\n", " clinical_data = pd.DataFrame(sample_chars)\n", " print(\"Extracted sample characteristics from series matrix\")\n", "elif family_soft is not None:\n", " print(f\"Found family soft file: {family_soft}\")\n", " # Similar processing for soft file if needed\n", " # For now, let's assume we can't process this without more specific parsing\n", " clinical_data = None\n", "else:\n", " # Try to find any file that might contain the word \"matrix\"\n", " matrix_files = [f for f in input_files if 'matrix' in f.lower()]\n", " if matrix_files:\n", " try:\n", " clinical_data = pd.read_csv(os.path.join(in_cohort_dir, matrix_files[0]))\n", " print(f\"Using matrix file: {matrix_files[0]}\")\n", " except:\n", " clinical_data = None\n", "\n", "# Check if we were able to load clinical data\n", "trait_row = None\n", "age_row = None\n", "gender_row = None\n", "\n", "if clinical_data is not None and not clinical_data.empty:\n", " print(\"\\nDataset structure:\")\n", " print(clinical_data.head())\n", " \n", " # Explore the unique values in each row to identify clinical features\n", " print(\"\\nUnique values by row:\")\n", " for i in range(min(20, len(clinical_data))):\n", " unique_values = clinical_data.iloc[i].unique()\n", " if len(unique_values) <= 10: # Only show if there are few unique values\n", " print(f\"Row {i}: {unique_values}\")\n", " \n", " # Based on our exploration, determine if gene expression data is available\n", " # For GEO data, we can assume gene expression data is available if we found\n", " # a matrix file or series matrix, but this would need better confirmation\n", " is_gene_available = True\n", " \n", " # Now let's carefully determine which rows contain trait, age, and gender information\n", " # These would be set based on the actual exploration of the data\n", " for i in range(min(20, len(clinical_data))):\n", " row_values = [str(x).lower() for x in clinical_data.iloc[i].unique() if str(x).strip()]\n", " \n", " # Check if this row might contain trait information (osteoporosis)\n", " if any(trait.lower() in str(x).lower() for x in row_values) or \\\n", " any(word in ' '.join(row_values) for word in ['osteoporosis', 'bmd', 'bone mineral density']):\n", " trait_row = i\n", " \n", " # Check if this row might contain age information\n", " if any(word in ' '.join(row_values) for word in ['age', 'year']):\n", " age_row = i\n", " \n", " # Check if this row might contain gender information\n", " if any(word in ' '.join(row_values) for word in ['gender', 'sex', 'male', 'female']):\n", " gender_row = i\n", " \n", " print(f\"\\nIdentified rows: trait_row={trait_row}, age_row={age_row}, gender_row={gender_row}\")\n", "else:\n", " print(\"No clinical data found in any of the expected formats\")\n", " is_gene_available = False\n", " clinical_data = pd.DataFrame()\n", "\n", "# Define conversion functions based on the data structure\n", "def convert_trait(value):\n", " \"\"\"Convert trait value to binary (0 or 1)\"\"\"\n", " if pd.isna(value) or value is None:\n", " return None\n", " \n", " # Extract value after colon if present\n", " if isinstance(value, str) and ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Convert to binary based on osteoporosis indicators\n", " value = str(value).lower()\n", " \n", " if any(term in value for term in ['osteoporosis', 'positive', 'yes', 'case', 'patient', 'fracture']):\n", " return 1\n", " elif any(term in value for term in ['control', 'negative', 'no', 'normal', 'healthy']):\n", " return 0\n", " else:\n", " # Try to interpret based on BMD values if present\n", " if 'bmd' in value or 'bone mineral density' in value:\n", " # Lower BMD usually indicates osteoporosis risk\n", " bmd_match = re.search(r'(\\d+\\.?\\d*)', value)\n", " if bmd_match:\n", " bmd_value = float(bmd_match.group(1))\n", " # This threshold is an example and would need adjustment\n", " return 1 if bmd_value < 0.8 else 0\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age value to continuous number\"\"\"\n", " if pd.isna(value) or value is None:\n", " return None\n", " \n", " # Extract value after colon if present\n", " if isinstance(value, str) and ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Try to extract numeric value\n", " if isinstance(value, str):\n", " # Remove non-numeric characters except decimal point\n", " numeric_part = re.search(r'(\\d+\\.?\\d*)', value)\n", " if numeric_part:\n", " return float(numeric_part.group(1))\n", " elif isinstance(value, (int, float)):\n", " return float(value)\n", " \n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender value to binary (0 for female, 1 for male)\"\"\"\n", " if pd.isna(value) or value is None:\n", " return None\n", " \n", " # Extract value after colon if present\n", " if isinstance(value, str) and ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Convert to binary\n", " value = str(value).lower()\n", " \n", " if any(term in value for term in ['female', 'f', 'woman', 'women']):\n", " return 0\n", " elif any(term in value for term in ['male', 'm', 'man', 'men']):\n", " return 1\n", " else:\n", " return None\n", "\n", "# Determine trait availability based on trait_row\n", "is_trait_available = trait_row is not None\n", "\n", "# Save initial metadata about dataset usability\n", "validate_and_save_cohort_info(\n", " is_final=False,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=is_\n" ] }, { "cell_type": "markdown", "id": "a4b48866", "metadata": {}, "source": [ "### Step 4: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "99fda7ed", "metadata": {}, "outputs": [], "source": [ "I'll implement the fixed code for the current step, addressing the file encoding/compression issues.\n", "\n", "```python\n", "import os\n", "import pandas as pd\n", "import numpy as np\n", "import json\n", "import gzip\n", "import io\n", "from typing import Optional, Callable, Dict, Any\n", "\n", "# Function to check if file is gzipped\n", "def is_gzipped(filepath):\n", " with open(filepath, 'rb') as test_f:\n", " return test_f.read(2) == b'\\x1f\\x8b'\n", "\n", "# Find and load the series matrix file\n", "series_matrix_files = [f for f in os.listdir(in_cohort_dir) if 'series_matrix' in f.lower()]\n", "if not series_matrix_files:\n", " # If no series matrix file, check for other txt files\n", " series_matrix_files = [f for f in os.listdir(in_cohort_dir) if f.endswith('.txt') or f.endswith('.txt.gz')]\n", "\n", "if not series_matrix_files:\n", " is_gene_available = False\n", " is_trait_available = False\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", " print(f\"No series matrix file found in {in_cohort_dir}\")\n", "else:\n", " series_matrix_file = os.path.join(in_cohort_dir, series_matrix_files[0])\n", " \n", " # Read the series matrix file with proper compression handling\n", " try:\n", " if is_gzipped(series_matrix_file) or series_matrix_file.endswith('.gz'):\n", " with gzip.open(series_matrix_file, 'rt', encoding='latin1') as f:\n", " lines = f.readlines()\n", " else:\n", " with open(series_matrix_file, 'r', encoding='latin1') as f: # Try a different encoding\n", " lines = f.readlines()\n", " except Exception as e:\n", " print(f\"Error reading file: {e}\")\n", " # If there's an error reading the file, set both to False\n", " is_gene_available = False\n", " is_trait_available = False\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", " raise\n", " \n", " # Extract sample characteristics\n", " sample_char_lines = []\n", " for i, line in enumerate(lines):\n", " if line.startswith('!Sample_characteristics'):\n", " sample_char_lines.append(line.strip())\n", " \n", " # Create a dictionary to store unique values for each characteristic\n", " char_values_dict = {}\n", " for i, line in enumerate(sample_char_lines):\n", " parts = line.split('\\t')\n", " if len(parts) < 2:\n", " continue\n", " \n", " # Extract the characteristic name and values\n", " header_part = parts[0]\n", " values = parts[1:]\n", " \n", " # Store in the dictionary\n", " if i not in char_values_dict:\n", " char_values_dict[i] = values\n", " \n", " # Convert to DataFrame for easier processing\n", " clinical_data = pd.DataFrame.from_dict(char_values_dict, orient='index')\n", " \n", " # Print unique values for analysis\n", " unique_values = {}\n", " for i in range(len(clinical_data)):\n", " unique_values[i] = clinical_data.iloc[i].unique().tolist()\n", " \n", " print(\"Unique values in each row:\")\n", " for row, values in unique_values.items():\n", " print(f\"Row {row}: {values}\")\n", " \n", " # 1. Check if gene expression data is available\n", " # Look for gene expression data in the matrix section of the file\n", " is_gene_section = False\n", " gene_lines = []\n", " for line in lines:\n", " if line.startswith('!series_matrix_table_begin'):\n", " is_gene_section = True\n", " continue\n", " if line.startswith('!series_matrix_table_end'):\n", " break\n", " if is_gene_section:\n", " gene_lines.append(line)\n", " \n", " is_gene_available = len(gene_lines) > 2 # At least header and some gene rows\n", " \n", " # 2. Analyze clinical data for trait, age, and gender information\n", " # 2.1 Data Availability\n", " trait_row = None\n", " age_row = None\n", " gender_row = None\n", " \n", " # Look through the unique values dictionary to find relevant rows\n", " for row, values in unique_values.items():\n", " values_str = str(values).lower()\n", " \n", " # Check for trait-related terms (Osteoporosis)\n", " if any(term in values_str for term in [\"osteoporosis\", \"bmd\", \"bone mineral density\", \"t-score\", \"osteopenia\"]):\n", " trait_row = row\n", " \n", " # Check for age-related terms\n", " if \"age\" in values_str or any(f\"year\" in values_str) or any(f\"{age}\" in values_str for age in range(20, 100)):\n", " age_row = row\n", " \n", " # Check for gender-related terms\n", " if any(term in values_str for term in [\"gender\", \"sex\", \"male\", \"female\"]):\n", " gender_row = row\n", " \n", " # 2.2 Data Type Conversion Functions\n", " def convert_trait(value):\n", " if pd.isna(value) or value is None:\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 osteoporosis, 0 for control/normal\n", " if any(term in value for term in [\"osteoporosis\", \"low bmd\", \"low bone mineral density\", \"osteopenia\", \"t-score < -2.5\"]):\n", " return 1\n", " elif any(term in value for term in [\"control\", \"normal\", \"healthy\", \"non-osteoporotic\", \"t-score > -1\"]):\n", " return 0\n", " else:\n", " return None\n", " \n", " def convert_age(value):\n", " if pd.isna(value) or value is None:\n", " return None\n", " \n", " value = str(value)\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " # Try to extract numeric age\n", " try:\n", " # Extract digits from the string\n", " import re\n", " age_match = re.search(r'(\\d+(\\.\\d+)?)', value)\n", " if age_match:\n", " return float(age_match.group(1))\n", " else:\n", " return None\n", " except:\n", " return None\n", " \n", " def convert_gender(value):\n", " if pd.isna(value) or value is None:\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: 0 for female, 1 for male\n", " if any(term in value for term in [\"female\", \"f\", \"woman\", \"women\"]):\n", " return 0\n", " elif any(term in value for term in [\"male\", \"m\", \"man\", \"men\"]):\n", " return 1\n", " else:\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", " # 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 if age_row is not None else None,\n" ] }, { "cell_type": "markdown", "id": "7e6817e7", "metadata": {}, "source": [ "### Step 5: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "63d38faf", "metadata": {}, "outputs": [], "source": [ "# 1. Get the file paths for the SOFT file and matrix file\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# 2. Use the get_genetic_data function from the library to get the gene_data from the matrix_file\n", "gene_data = get_genetic_data(matrix_file)\n", "\n", "# 3. Print the first 20 row IDs (gene or probe identifiers) for future observation\n", "print(gene_data.index[:20])\n" ] }, { "cell_type": "markdown", "id": "db1cd71e", "metadata": {}, "source": [ "### Step 6: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": null, "id": "346bad64", "metadata": {}, "outputs": [], "source": [ "# Examining the gene identifiers in the index\n", "# The identifiers are numeric strings ('1', '2', '3', etc.) which are not standard human gene symbols\n", "# Human gene symbols are typically alphanumeric, like 'BRCA1', 'TP53', etc.\n", "# These appear to be probe IDs or some other internal identifiers that need mapping to gene symbols\n", "\n", "requires_gene_mapping = True" ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 5 }