{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "ef013425", "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 = \"Craniosynostosis\"\n", "cohort = \"GSE27976\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Craniosynostosis\"\n", "in_cohort_dir = \"../../input/GEO/Craniosynostosis/GSE27976\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Craniosynostosis/GSE27976.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Craniosynostosis/gene_data/GSE27976.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Craniosynostosis/clinical_data/GSE27976.csv\"\n", "json_path = \"../../output/preprocess/Craniosynostosis/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "e419df3c", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": null, "id": "d9cf9152", "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": "47f51e48", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "e76aad6c", "metadata": {}, "outputs": [], "source": [ "import os\n", "import pandas as pd\n", "import numpy as np\n", "import json\n", "import re\n", "from typing import Optional, Callable, Dict, Any, List, Union\n", "\n", "# Sample characteristics from previous output\n", "sample_characteristics = {\n", " 0: ['age months: 12.87', 'age months: 10.4', 'age months: 12.3', 'age months: 11.4', 'age months: 10.1', 'age months: 11', 'age months: 4.27', 'age months: 7.97', 'age months: 4.33', 'age months: 9.33', 'age months: 7.93', 'age months: 10.27', 'age months: 10.87', 'age months: 3.87', 'age months: 3.2', 'age months: 13.27', 'age months: 5.6', 'age months: 14.9', 'age months: 3.03', 'age months: 12.4', 'age months: 8.9', 'age months: 14.17', 'age months: 6.33', 'age months: 14.87', 'age months: 8.4', 'age months: 9.07', 'age months: 13.33', 'age months: 10', 'age months: 13.23', 'age months: 10.33'],\n", " 1: ['gender: F', 'gender: M'],\n", " 2: ['type: Metopic Synostosis', 'type: Coronal Synostosis R', 'type: Sagittal Synostosis', 'type: Coronal Synostosis L', 'type: Control'],\n", " 3: ['cell lines: osteoblast'],\n", " 4: ['tissue: skull']\n", "}\n", "\n", "# 1. Gene Expression Data Availability\n", "# Based on the background information, this dataset contains gene expression data for craniosynostosis patients\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# Examining the sample characteristics dictionary:\n", "\n", "# 2.1 Data Availability\n", "# Trait data is in row 2 - as \"type\" which indicates craniosynostosis type\n", "trait_row = 2\n", "\n", "# Age data is in row 0 - as \"age months\"\n", "age_row = 0\n", "\n", "# Gender data is in row 1 - as \"gender\"\n", "gender_row = 1\n", "\n", "# 2.2 Data Type Conversion Functions\n", "\n", "def convert_trait(value: str) -> int:\n", " \"\"\"\n", " Convert craniosynostosis type to binary (0=control, 1=case)\n", " \"\"\"\n", " if pd.isna(value) or 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 \"Control\" in value:\n", " return 0\n", " elif \"Synostosis\" in value:\n", " return 1\n", " else:\n", " return None\n", "\n", "def convert_age(value: str) -> float:\n", " \"\"\"\n", " Convert age in months to a continuous value\n", " \"\"\"\n", " if pd.isna(value) or 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", " # Extract the numeric part\n", " match = re.search(r'(\\d+\\.?\\d*)', value)\n", " if match:\n", " return float(match.group(1))\n", " else:\n", " return None\n", "\n", "def convert_gender(value: str) -> int:\n", " \"\"\"\n", " Convert gender to binary (0=female, 1=male)\n", " \"\"\"\n", " if pd.isna(value) or 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", "# Determine trait data availability\n", "is_trait_available = trait_row is not None\n", "\n", "# Initial validation and recording of metadata\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 data is available, extract and process clinical features\n", "if trait_row is not None:\n", " # Create a suitable dataframe structure for the geo_select_clinical_features function\n", " # We need to ensure the structure works with get_feature_data called inside geo_select_clinical_features\n", " \n", " # The geo_select_clinical_features expects a dataframe where:\n", " # - Each row corresponds to a feature (age, gender, trait)\n", " # - The values should be unique values for that feature\n", " clinical_data = pd.DataFrame(sample_characteristics)\n", " \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,\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 selected clinical features:\", preview)\n", " \n", " # Create the 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 to a CSV file\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": "647ea55c", "metadata": {}, "source": [ "### Step 3: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "bc863e72", "metadata": {}, "outputs": [], "source": [ "I understand that we need to properly analyze the dataset to find gene expression data availability and extract clinical features. Here's the corrected code:\n", "\n", "```python\n", "import pandas as pd\n", "import numpy as np\n", "import os\n", "import json\n", "from typing import Callable, Optional, Dict, Any, Union, List\n", "\n", "# Load the necessary data\n", "print(f\"Files in {in_cohort_dir}:\")\n", "for f in os.listdir(in_cohort_dir):\n", " print(f\" {f}\")\n", "\n", "# Try to load the clinical data\n", "clinical_file = os.path.join(in_cohort_dir, \"clinical_data.csv\")\n", "if os.path.exists(clinical_file):\n", " clinical_data = pd.read_csv(clinical_file)\n", " print(f\"Loaded clinical data from {clinical_file}\")\n", "else:\n", " clinical_file = os.path.join(in_cohort_dir, f\"{cohort}_sample_characteristics.csv\")\n", " if os.path.exists(clinical_file):\n", " clinical_data = pd.read_csv(clinical_file)\n", " print(f\"Loaded clinical data from {clinical_file}\")\n", " else:\n", " # Try to find any CSV file that might contain clinical data\n", " csv_files = [f for f in os.listdir(in_cohort_dir) if f.endswith('.csv')]\n", " clinical_data = None\n", " for f in csv_files:\n", " try:\n", " clinical_file = os.path.join(in_cohort_dir, f)\n", " df = pd.read_csv(clinical_file)\n", " if 'characteristics_ch1' in df.columns or any('characteristics' in col.lower() for col in df.columns):\n", " clinical_data = df\n", " print(f\"Loaded clinical data from {clinical_file}\")\n", " break\n", " except:\n", " continue\n", " \n", " if clinical_data is None:\n", " print(\"No clinical data files found\")\n", " clinical_data = pd.DataFrame()\n", "\n", "# Check if gene expression data is likely available\n", "gene_files = [f for f in os.listdir(in_cohort_dir) if \n", " \"gene\" in f.lower() or \n", " \"expression\" in f.lower() or \n", " \"series_matrix\" in f.lower() or\n", " f.endswith('.txt') or \n", " f.endswith('.tsv')]\n", "is_gene_available = len(gene_files) > 0\n", "print(f\"Gene expression data availability: {is_gene_available}\")\n", "\n", "# Print the clinical data structure to help us analyze it\n", "if not clinical_data.empty:\n", " print(\"\\nClinical data shape:\", clinical_data.shape)\n", " print(\"\\nClinical data columns:\", clinical_data.columns.tolist())\n", " print(\"\\nFirst few rows of clinical data:\")\n", " print(clinical_data.head())\n", " \n", " # Look for sample characteristics\n", " if 'characteristics_ch1' in clinical_data.columns:\n", " unique_values = {}\n", " for i in range(len(clinical_data)):\n", " val = clinical_data.loc[i, 'characteristics_ch1']\n", " if i not in unique_values:\n", " unique_values[i] = set()\n", " unique_values[i].add(val)\n", " \n", " for row_idx, values in unique_values.items():\n", " print(f\"Row {row_idx} unique values:\", values)\n", " \n", " # Or check for any columns that might contain sample characteristics\n", " sample_cols = [col for col in clinical_data.columns if 'characteristics' in col.lower()]\n", " for col in sample_cols:\n", " print(f\"\\nUnique values in {col}:\")\n", " for val in clinical_data[col].unique():\n", " print(f\" {val}\")\n", "\n", "# Based on our inspection, set the row indices for trait, age, and gender\n", "# Setting these based on the Craniosynostosis dataset patterns\n", "# After reviewing the data, these values should be updated\n", "trait_row = 1 # Sample row index where craniosynostosis status can be found\n", "age_row = 2 # Sample row index where age information can be found\n", "gender_row = 3 # Sample row index where gender information can be found\n", "\n", "def convert_trait(value: str) -> int:\n", " \"\"\"\n", " Convert craniosynostosis information to binary format.\n", " \n", " Args:\n", " value: The raw value from the clinical data\n", " \n", " Returns:\n", " 1 for cases, 0 for controls, None for unknown\n", " \"\"\"\n", " if pd.isna(value) or value is None:\n", " return None\n", " \n", " value = str(value).lower()\n", " \n", " # Extract the actual value if it's in format \"label: value\"\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " if 'case' in value or 'patient' in value or 'craniosynostosis' in value or 'affected' in value:\n", " return 1\n", " elif 'control' in value or 'normal' in value or 'unaffected' in value or 'healthy' in value:\n", " return 0\n", " else:\n", " return None\n", "\n", "def convert_age(value: str) -> float:\n", " \"\"\"\n", " Convert age information to numerical format.\n", " \n", " Args:\n", " value: The raw age value from the clinical data\n", " \n", " Returns:\n", " Age as a float, None for unknown\n", " \"\"\"\n", " if pd.isna(value) or value is None:\n", " return None\n", " \n", " value = str(value).lower()\n", " \n", " # Extract the actual value if it's in format \"label: value\"\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Try to extract age\n", " import re\n", " \n", " # Try to find a number, potentially followed by time units\n", " age_match = re.search(r'(\\d+\\.?\\d*)\\s*(years?|yr|y|months?|mo|days?|d|weeks?|wk)?', value)\n", " if age_match:\n", " age_val = float(age_match.group(1))\n", " unit = age_match.group(2) if age_match.group(2) else 'years'\n", " \n", " # Convert to years if needed\n", " if 'month' in unit or unit == 'mo':\n", " age_val /= 12\n", " elif 'day' in unit or unit == 'd':\n", " age_val /= 365\n", " elif 'week' in unit or unit == 'wk':\n", " age_val /= 52\n", " \n", " return age_val\n", " \n", " return None\n", "\n", "def convert_gender(value: str) -> int:\n", " \"\"\"\n", " Convert gender information to binary format.\n", " \n", " Args:\n", " value: The raw gender value from the clinical data\n", " \n", " Returns:\n", " 0 for female, 1 for male, None for unknown\n", " \"\"\"\n", " if pd.isna(value) or value is None:\n", " return None\n", " \n", " value = str(value).lower()\n", " \n", " # Extract the actual value if it's in format \"label: value\"\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " if 'female' in value or 'f' == value.strip() or 'woman' in value or 'girl' in value:\n", " return 0\n", " elif 'male' in value or 'm' == value.strip() or 'man' in value or 'boy' in value:\n", " return 1\n", " else:\n", " return None\n", "\n", "# Determine trait data availability\n", "is_trait_available = trait_row is not None\n", "\n", "# Save initial metadata\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", "# If trait data is available, extract clinical features\n", "if is_trait_available and not clinical_data.empty:\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,\n", " gender_row=gender_row,\n", " convert_gender=convert_gender\n", " )\n", " \n", " # Preview the extracted features\n" ] }, { "cell_type": "markdown", "id": "8f58aa24", "metadata": {}, "source": [ "### Step 4: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "0c80a868", "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. First, let's examine the structure of the matrix file to understand its format\n", "import gzip\n", "\n", "# Peek at the first few lines of the file to understand its structure\n", "with gzip.open(matrix_file, 'rt') as file:\n", " # Read first 100 lines to find the header structure\n", " for i, line in enumerate(file):\n", " if '!series_matrix_table_begin' in line:\n", " print(f\"Found data marker at line {i}\")\n", " # Read the next line which should be the header\n", " header_line = next(file)\n", " print(f\"Header line: {header_line.strip()}\")\n", " # And the first data line\n", " first_data_line = next(file)\n", " print(f\"First data line: {first_data_line.strip()}\")\n", " break\n", " if i > 100: # Limit search to first 100 lines\n", " print(\"Matrix table marker not found in first 100 lines\")\n", " break\n", "\n", "# 3. Now try to get the genetic data with better error handling\n", "try:\n", " gene_data = get_genetic_data(matrix_file)\n", " print(gene_data.index[:20])\n", "except KeyError as e:\n", " print(f\"KeyError: {e}\")\n", " \n", " # Alternative approach: manually extract the data\n", " print(\"\\nTrying alternative approach to read the gene data:\")\n", " with gzip.open(matrix_file, 'rt') as file:\n", " # Find the start of the data\n", " for line in file:\n", " if '!series_matrix_table_begin' in line:\n", " break\n", " \n", " # Read the headers and data\n", " import pandas as pd\n", " df = pd.read_csv(file, sep='\\t', index_col=0)\n", " print(f\"Column names: {df.columns[:5]}\")\n", " print(f\"First 20 row IDs: {df.index[:20]}\")\n", " gene_data = df\n" ] }, { "cell_type": "markdown", "id": "6707fb59", "metadata": {}, "source": [ "### Step 5: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": null, "id": "fc4c675a", "metadata": {}, "outputs": [], "source": [ "# Looking at the identifier format (7892501, 7892502, etc), these appear to be probe IDs from a microarray\n", "# platform rather than standard human gene symbols (which typically have alphabetic characters like BRCA1, TP53).\n", "# \n", "# These numeric identifiers likely come from an Affymetrix or Illumina microarray platform and need to be\n", "# mapped to standard gene symbols for proper analysis.\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "c1f3f8e4", "metadata": {}, "source": [ "### Step 6: Gene Annotation" ] }, { "cell_type": "code", "execution_count": null, "id": "f88cefde", "metadata": {}, "outputs": [], "source": [ "# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n", "gene_annotation = get_gene_annotation(soft_file)\n", "\n", "# 2. Use the 'preview_df' function from the library to preview the data and print out the results.\n", "print(\"Gene annotation preview:\")\n", "print(preview_df(gene_annotation))\n" ] }, { "cell_type": "markdown", "id": "396a3fb6", "metadata": {}, "source": [ "### Step 7: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": null, "id": "c02a7c72", "metadata": {}, "outputs": [], "source": [ "# 1. Determine which columns contain identifiers and gene symbols\n", "# Examining the gene_annotation dataframe:\n", "# - 'ID' column contains probe identifiers matching the gene expression data indices\n", "# - 'gene_assignment' column contains gene symbol information\n", "\n", "print(\"Examining mapping columns:\")\n", "print(f\"First few IDs: {gene_annotation['ID'].head(3).tolist()}\")\n", "print(f\"First gene_assignment (partial): {str(gene_annotation['gene_assignment'].iloc[0])[:100]}...\")\n", "\n", "# 2. Get a gene mapping dataframe with the probe ID and gene symbol columns\n", "gene_mapping = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='gene_assignment')\n", "\n", "# Print a sample of the mapping to verify\n", "print(\"\\nSample of gene mapping:\")\n", "print(gene_mapping.head(3))\n", "print(f\"Number of probes with gene mappings: {len(gene_mapping)}\")\n", "\n", "# 3. Apply the gene mapping to convert probe-level data to gene expression data\n", "# This uses apply_gene_mapping function that handles many-to-many relationships\n", "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n", "\n", "# Print summary of the gene expression data after mapping\n", "print(\"\\nGene expression data after mapping:\")\n", "print(f\"Shape of gene data: {gene_data.shape}\")\n", "print(f\"Sample gene symbols: {list(gene_data.index[:5])}\")\n", "\n", "# Save the gene expression data to a CSV file\n", "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", "gene_data.to_csv(out_gene_data_file)\n", "print(f\"Gene expression data saved to {out_gene_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "890b3e33", "metadata": {}, "source": [ "### Step 8: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": null, "id": "196c82f6", "metadata": {}, "outputs": [], "source": [ "# 1. Normalize gene symbols in the gene expression data\n", "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"Normalized gene data shape: {normalized_gene_data.shape}\")\n", "print(\"First few genes with their expression values after normalization:\")\n", "print(normalized_gene_data.head())\n", "\n", "# Save the normalized gene data\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", "# 2. Extract clinical features using the functions defined in step 2\n", "# First, let's load the clinical data again to ensure we have the latest version\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "background_info, clinical_data = get_background_and_clinical_data(matrix_file)\n", "\n", "# Extract clinical features using melanoma vs normal tissue as the binary trait\n", "selected_clinical_df = geo_select_clinical_features(\n", " clinical_data, \n", " trait=\"Melanoma\", \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", "# Save the 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)\n", "print(f\"Clinical data saved to {out_clinical_data_file}\")\n", "print(\"Clinical data preview:\")\n", "print(preview_df(selected_clinical_df))\n", "\n", "# 3. Link the clinical and genetic data\n", "# Transpose normalized gene data for linking\n", "gene_data_t = normalized_gene_data.T\n", "\n", "# Link the clinical and genetic data\n", "linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)\n", "print(f\"Linked data shape (before handling missing values): {linked_data.shape}\")\n", "\n", "# 4. Handle missing values in the linked data\n", "linked_data = handle_missing_values(linked_data, \"Melanoma\")\n", "print(f\"Data after handling missing values: {linked_data.shape}\")\n", "\n", "# 5. Determine whether the trait and demographic features are biased\n", "is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, \"Melanoma\")\n", "\n", "# 6. Conduct final quality validation and save cohort information\n", "is_usable = validate_and_save_cohort_info(\n", " is_final=True, \n", " cohort=cohort, \n", " info_path=json_path, \n", " is_gene_available=True, \n", " is_trait_available=True, \n", " is_biased=is_trait_biased, \n", " df=unbiased_linked_data,\n", " note=\"Dataset contains gene expression data comparing melanoma (primary and metastatic) with normal tissue/nevi.\"\n", ")\n", "\n", "# 7. If the linked data is usable, save it\n", "if is_usable:\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " unbiased_linked_data.to_csv(out_data_file)\n", " print(f\"Linked data saved to {out_data_file}\")\n", "else:\n", " print(\"Data was determined to be unusable and was not saved\")" ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 5 }