{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "525b4fe7", "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 = \"Underweight\"\n", "cohort = \"GSE131835\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Underweight\"\n", "in_cohort_dir = \"../../input/GEO/Underweight/GSE131835\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Underweight/GSE131835.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Underweight/gene_data/GSE131835.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Underweight/clinical_data/GSE131835.csv\"\n", "json_path = \"../../output/preprocess/Underweight/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "f19f838b", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": null, "id": "5f49d039", "metadata": {}, "outputs": [], "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": "8a65a3cf", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "77ff6071", "metadata": {}, "outputs": [], "source": [ "import pandas as pd\n", "import os\n", "import json\n", "\n", "# 1. Gene Expression Data Availability\n", "# From the background information, we can see this dataset uses Affymetrix Clariom S Microarray\n", "# which is used for gene expression profiling, so gene expression data is available.\n", "is_gene_available = True\n", "\n", "# 2. Data Availability and Conversion Functions\n", "\n", "# 2.1 Trait (Underweight)\n", "# From the background information, we can see this study is about cancer cachexia,\n", "# which is characterized by weight loss. The trait \"Underweight\" can be associated\n", "# with the 'group' field at index 1, which has categories 'CWL' (Cancer Weight Loss),\n", "# 'CWS' (Cancer Weight Stable), and 'CONTROL'.\n", "trait_row = 1\n", "\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 the value after colon if present\n", " if isinstance(value, str) and ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # CWL (Cancer Weight Loss) corresponds to underweight\n", " if value == 'CWL':\n", " return 1\n", " # CWS (Cancer Weight Stable) and CONTROL are not underweight\n", " elif value in ['CWS', 'CONTROL', 'CONTROl']:\n", " return 0\n", " else:\n", " return None\n", "\n", "# 2.2 Age\n", "# Age information is available in the sample characteristics at index 3\n", "age_row = 3\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age value to continuous numeric value\"\"\"\n", " if pd.isna(value) or value is None:\n", " return None\n", " \n", " # Extract the value after colon if present\n", " if isinstance(value, str) and ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " try:\n", " return float(value)\n", " except (ValueError, TypeError):\n", " return None\n", "\n", "# 2.3 Gender\n", "# Gender information is available in the sample characteristics at index 2\n", "gender_row = 2\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 the value after colon if present\n", " if isinstance(value, str) and ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " if value.lower() == 'female':\n", " return 0\n", " elif value.lower() == 'male':\n", " return 1\n", " else:\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Determine if trait data is available\n", "is_trait_available = trait_row is not None\n", "\n", "# Validate and save cohort info (initial filtering)\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, extract clinical features\n", "if trait_row is not None:\n", " # The sample characteristics dictionary was shown in the previous output\n", " # This data is typically stored in the series_matrix.txt.gz file\n", " # We'll use the available matrix file path to load it\n", " \n", " # Load the data from the matrix file path\n", " matrix_file_path = os.path.join(in_cohort_dir, \"GSE131835_series_matrix.txt.gz\")\n", " \n", " # Access clinical data from the provided file\n", " # Since we're dealing with a GEO dataset, we'll use the appropriate tools\n", " # from the tools.preprocess module to load the clinical data\n", " clinical_data = pd.read_pickle(os.path.join(\"./output/parse\", f\"{cohort}_clinical_data.pkl\"))\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 extracted clinical features\n", " clinical_preview = preview_df(selected_clinical_df)\n", " print(\"Preview of extracted clinical features:\")\n", " print(clinical_preview)\n", " \n", " # Save clinical data to CSV\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " selected_clinical_df.to_csv(out_clinical_data_file, index=True)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "e3e86e4d", "metadata": {}, "source": [ "### Step 3: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "7449cc39", "metadata": {}, "outputs": [], "source": [ "# First, let's define data availability by analyzing the previous step output\n", "\n", "# Since the previous step's output is empty, we need to load and analyze the data ourselves\n", "import pandas as pd\n", "import os\n", "import json\n", "from typing import Callable, Optional, Dict, Any\n", "\n", "# Let's first try to load the clinical data\n", "clinical_data_file = os.path.join(in_cohort_dir, \"clinical_data.csv\")\n", "gene_data_file = os.path.join(in_cohort_dir, \"gene_data.csv\")\n", "\n", "# Check if the files exist\n", "is_gene_available = os.path.exists(gene_data_file)\n", "is_clinical_data_available = os.path.exists(clinical_data_file)\n", "\n", "# Load clinical data if available\n", "if is_clinical_data_available:\n", " clinical_data = pd.read_csv(clinical_data_file)\n", " # Preview the clinical data to understand structure\n", " print(\"Clinical data preview:\")\n", " print(clinical_data.head())\n", " \n", " # Check for unique values in each row to identify trait, age, and gender\n", " sample_characteristics = {}\n", " for i, row in clinical_data.iterrows():\n", " unique_values = row.drop(row.index[0]).unique()\n", " sample_characteristics[i] = list(unique_values)\n", " print(f\"Row {i}: {list(unique_values)}\")\n", "else:\n", " print(\"Clinical data not available\")\n", " clinical_data = None\n", " sample_characteristics = {}\n", "\n", "# Based on the analysis, define trait_row, age_row, and gender_row\n", "# Since we don't have output from the previous step, we'll make educated guesses\n", "# These would be updated after seeing the actual data\n", "\n", "# If we can't determine from the output, we'll set them to None initially\n", "trait_row = None\n", "age_row = None\n", "gender_row = None\n", "\n", "# Define conversion functions\n", "def convert_trait(value):\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 underweight status\n", " value = value.lower()\n", " if 'underweight' in value or 'low bmi' in value:\n", " return 1\n", " elif 'normal' in value or 'healthy' in value:\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", " # 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 numeric age\n", " try:\n", " # Remove any non-numeric characters (except decimal point)\n", " numeric_value = ''.join(c for c in value if c.isdigit() or c == '.')\n", " return float(numeric_value)\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", " # 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 gender\n", " value = value.lower()\n", " if 'female' in value or 'f' == value:\n", " return 0\n", " elif 'male' in value or 'm' == value:\n", " return 1\n", " else:\n", " return None\n", "\n", "# Before finalizing, let's check if we have any clinical data and extract more information\n", "if is_clinical_data_available and clinical_data is not None:\n", " # This is a placeholder - we would analyze actual data here\n", " # Without the actual data, we're making an educated guess\n", " \n", " # For simplicity, we'll assume trait_row is None until we can verify from the data\n", " # This indicates we don't have trait data currently\n", " pass\n", "\n", "# Validate and save cohort info\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", "# If clinical data is available and trait_row is not None, extract clinical features\n", "if is_clinical_data_available and trait_row is not None:\n", " selected_clinical_data = 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 extracted data\n", " preview = preview_df(selected_clinical_data)\n", " print(\"Selected clinical data preview:\")\n", " print(preview)\n", " \n", " # Save the extracted clinical features\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " selected_clinical_data.to_csv(out_clinical_data_file, index=False)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n", "else:\n", " print(\"Clinical feature extraction skipped - no trait data available\")\n" ] }, { "cell_type": "markdown", "id": "858e98d7", "metadata": {}, "source": [ "### Step 4: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "3f73e030", "metadata": {}, "outputs": [], "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": "7e329ee4", "metadata": {}, "source": [ "### Step 5: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": null, "id": "84916bc9", "metadata": {}, "outputs": [], "source": [ "# These identifiers appear to be Ensembl gene IDs with \"_at\" suffix\n", "# Ensembl IDs start with \"ENSG\" for human genes, but they're not standard human gene symbols\n", "# They need to be mapped to standard gene symbols for better interpretability\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "39cfae06", "metadata": {}, "source": [ "### Step 6: Gene Annotation" ] }, { "cell_type": "code", "execution_count": null, "id": "085906ca", "metadata": {}, "outputs": [], "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": "26a390de", "metadata": {}, "source": [ "### Step 7: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": null, "id": "905a779f", "metadata": {}, "outputs": [], "source": [ "# 1. Identify which columns in gene annotation correspond to gene identifiers and gene symbols\n", "# From previous outputs we see:\n", "# - Gene expression data has identifiers like 'ENSG00000000003_at' in the index\n", "# - Gene annotation has 'ID' column with same format ('ENSG00000000003_at')\n", "# - The 'ORF' column in gene annotation contains gene symbols (e.g., 'TSPAN6')\n", "\n", "# 2. Extract the gene mapping between identifiers and symbols\n", "print(\"Creating gene mapping between identifiers and gene symbols...\")\n", "gene_mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='ORF')\n", "print(f\"Gene mapping shape: {gene_mapping_df.shape}\")\n", "print(\"Gene mapping preview:\")\n", "print(preview_df(gene_mapping_df))\n", "\n", "# 3. Apply the gene mapping to convert probe-level measurements to gene expression data\n", "print(\"\\nConverting probe-level measurements to gene expression data...\")\n", "gene_data = apply_gene_mapping(gene_data, gene_mapping_df)\n", "print(f\"Gene expression data shape after mapping: {gene_data.shape}\")\n", "print(\"First 5 gene symbols after mapping:\")\n", "print(gene_data.index[:5])\n", "\n", "# Save the processed gene expression data\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": "ca815223", "metadata": {}, "source": [ "### Step 8: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": null, "id": "63ec843b", "metadata": {}, "outputs": [], "source": [ "# 1. Load gene expression data from previously saved file or re-extract it\n", "import os\n", "import pandas as pd\n", "\n", "# Re-extract the gene data since variables from previous step are not available\n", "soft_file_path, matrix_file_path = geo_get_relevant_filepaths(in_cohort_dir)\n", "gene_data = get_genetic_data(matrix_file_path)\n", "\n", "# Get gene annotation and create mapping\n", "gene_annotation = get_gene_annotation(soft_file_path)\n", "gene_mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='ORF')\n", "gene_data = apply_gene_mapping(gene_data, gene_mapping_df)\n", "\n", "# Normalize gene symbols\n", "gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"Gene data shape after normalization: {gene_data.shape}\")\n", "print(f\"First few gene symbols after normalization: {list(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", "gene_data.to_csv(out_gene_data_file)\n", "print(f\"Normalized gene data saved to {out_gene_data_file}\")\n", "\n", "# 2. Extract and prepare clinical data\n", "# SOFT file contains the sample characteristics\n", "background_info, clinical_data = get_background_and_clinical_data(matrix_file_path)\n", "\n", "# From the sample characteristics in Step 1, we know:\n", "# - trait_row = 1 (group: CWL, CWS, CONTROL where CWL indicates weight loss)\n", "# - age_row = 3 (age information)\n", "# - gender_row = 2 (Sex information)\n", "\n", "trait_row = 1\n", "age_row = 3\n", "gender_row = 2\n", "\n", "def convert_trait(value):\n", " \"\"\"Convert Cancer Weight Loss to underweight status (binary)\"\"\"\n", " if pd.isna(value) or value is None:\n", " return None\n", " \n", " # Extract the value after colon if present\n", " if isinstance(value, str) and ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # CWL (Cancer Weight Loss) corresponds to underweight\n", " if value == 'CWL':\n", " return 1\n", " # CWS (Cancer Weight Stable) and CONTROL are not underweight\n", " elif value in ['CWS', 'CONTROL', 'CONTROl']:\n", " return 0\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age value to continuous numeric value\"\"\"\n", " if pd.isna(value) or value is None:\n", " return None\n", " \n", " # Extract the value after colon if present\n", " if isinstance(value, str) and ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " try:\n", " return float(value)\n", " except (ValueError, TypeError):\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 the value after colon if present\n", " if isinstance(value, str) and ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " if value.lower() == 'female':\n", " return 0\n", " elif value.lower() == 'male':\n", " return 1\n", " else:\n", " return None\n", "\n", "# Extract clinical features\n", "clinical_features = geo_select_clinical_features(\n", " 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", "print(\"Clinical features extracted:\")\n", "print(preview_df(clinical_features))\n", "\n", "# Save the clinical data\n", "os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", "clinical_features.to_csv(out_clinical_data_file)\n", "print(f\"Clinical data saved to {out_clinical_data_file}\")\n", "\n", "# 3. Link clinical and genetic data\n", "linked_data = geo_link_clinical_genetic_data(clinical_features, gene_data)\n", "print(f\"Linked data shape: {linked_data.shape}\")\n", "print(\"Linked data preview:\")\n", "print(preview_df(linked_data))\n", "\n", "# 4. Handle missing values\n", "linked_data = handle_missing_values(linked_data, trait)\n", "print(f\"Linked data shape after handling missing values: {linked_data.shape}\")\n", "\n", "# 5. Determine whether the trait and demographic features are biased\n", "is_trait_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n", "print(f\"Is trait biased: {is_trait_biased}\")\n", "\n", "# 6. Conduct quality check and save the cohort information\n", "note = \"Dataset contains gene expression data from adipose tissue samples comparing cancer patients with weight loss to controls.\"\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=linked_data,\n", " note=note\n", ")\n", "\n", "# 7. Save the linked data if it's usable\n", "print(f\"Data quality check result: {'Usable' if is_usable else 'Not usable'}\")\n", "if is_usable:\n", " # Create directory if it doesn't exist\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " linked_data.to_csv(out_data_file)\n", " print(f\"Linked data saved to {out_data_file}\")\n", "else:\n", " print(f\"Data not saved due to quality issues.\")" ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 5 }