{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "2d90e327", "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 = \"Sarcoma\"\n", "cohort = \"GSE159848\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Sarcoma\"\n", "in_cohort_dir = \"../../input/GEO/Sarcoma/GSE159848\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Sarcoma/GSE159848.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Sarcoma/gene_data/GSE159848.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Sarcoma/clinical_data/GSE159848.csv\"\n", "json_path = \"../../output/preprocess/Sarcoma/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "cfb958f5", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": null, "id": "ad0dbf1d", "metadata": {}, "outputs": [], "source": [ "# 1. Check what files are actually in the directory\n", "import os\n", "print(\"Files in the directory:\")\n", "files = os.listdir(in_cohort_dir)\n", "print(files)\n", "\n", "# 2. Find appropriate files with more flexible pattern matching\n", "soft_file = None\n", "matrix_file = None\n", "\n", "for file in files:\n", " file_path = os.path.join(in_cohort_dir, file)\n", " # Look for files that might contain SOFT or matrix data with various possible extensions\n", " if 'soft' in file.lower() or 'family' in file.lower() or file.endswith('.soft.gz'):\n", " soft_file = file_path\n", " if 'matrix' in file.lower() or file.endswith('.txt.gz') or file.endswith('.tsv.gz'):\n", " matrix_file = file_path\n", "\n", "if not soft_file:\n", " print(\"Warning: Could not find a SOFT file. Using the first .gz file as fallback.\")\n", " gz_files = [f for f in files if f.endswith('.gz')]\n", " if gz_files:\n", " soft_file = os.path.join(in_cohort_dir, gz_files[0])\n", "\n", "if not matrix_file:\n", " print(\"Warning: Could not find a matrix file. Using the second .gz file as fallback if available.\")\n", " gz_files = [f for f in files if f.endswith('.gz')]\n", " if len(gz_files) > 1 and soft_file != os.path.join(in_cohort_dir, gz_files[1]):\n", " matrix_file = os.path.join(in_cohort_dir, gz_files[1])\n", " elif len(gz_files) == 1 and not soft_file:\n", " matrix_file = os.path.join(in_cohort_dir, gz_files[0])\n", "\n", "print(f\"SOFT file: {soft_file}\")\n", "print(f\"Matrix file: {matrix_file}\")\n", "\n", "# 3. Read files if found\n", "if soft_file and matrix_file:\n", " # 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", " \n", " try:\n", " background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n", " \n", " # Obtain the sample characteristics dictionary from the clinical dataframe\n", " sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n", " \n", " # 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", " except Exception as e:\n", " print(f\"Error processing files: {e}\")\n", " # Try swapping files if first attempt fails\n", " print(\"Trying to swap SOFT and matrix files...\")\n", " temp = soft_file\n", " soft_file = matrix_file\n", " matrix_file = temp\n", " try:\n", " background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n", " sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n", " print(\"Background Information:\")\n", " print(background_info)\n", " print(\"Sample Characteristics Dictionary:\")\n", " print(sample_characteristics_dict)\n", " except Exception as e:\n", " print(f\"Still error after swapping: {e}\")\n", "else:\n", " print(\"Could not find necessary files for processing.\")\n" ] }, { "cell_type": "markdown", "id": "4ec756da", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "2a2f1321", "metadata": {}, "outputs": [], "source": [ "```python\n", "import pandas as pd\n", "import os\n", "import json\n", "from typing import Optional, Callable, Dict, Any\n", "\n", "# 1. Gene Expression Data Availability\n", "# Based on the series description and overall design, this dataset contains gene expression data from microarray\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "\n", "# For trait (sarcoma):\n", "# Looking at the sample characteristics, all samples are mixoid liposarcoma patients (row 2)\n", "# Since all samples are sarcoma patients, we need a binary trait for case-control analysis\n", "# We'll use the metastasis status (row 3) as our trait of interest since it has binary values (0, 1)\n", "trait_row = 3\n", "\n", "# For age:\n", "# Age is available in row 1\n", "age_row = 1\n", "\n", "# For gender:\n", "# Gender (Sex) is available in row 0\n", "gender_row = 0\n", "\n", "# 2.2 Data Type Conversion\n", "\n", "def convert_trait(value: str) -> Optional[int]:\n", " \"\"\"Convert metastasis status to binary.\"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract value after colon if present\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " try:\n", " return int(value) # 0 for no metastasis, 1 for metastasis\n", " except (ValueError, TypeError):\n", " return None\n", "\n", "def convert_age(value: str) -> Optional[float]:\n", " \"\"\"Convert age to continuous numeric value.\"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract value after colon if present\n", " if ':' 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: str) -> Optional[int]:\n", " \"\"\"Convert gender to binary (0 for female, 1 for male).\"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract value after colon if present\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Convert to lowercase for case-insensitive comparison\n", " value = value.lower()\n", " \n", " if value == 'f' or value == 'female':\n", " return 0\n", " elif value == 'm' or value == 'male':\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 filtering and save 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_row is not None:\n", " # In previous step the clinical data was parsed and is available in memory\n", " # We need to get it from the sample characteristics dictionary\n", " # Convert the dictionary to a DataFrame\n", " clinical_dict = {0: ['Sex: M', 'Sex: F'], \n", " 1: ['age: 44', 'age: 67', 'age: 54', 'age: 82', 'age: 47', 'age: 32', 'age: 57', \n", " 'age: 60', 'age: 51', 'age: 45', 'age: 38', 'age: 16', 'age: 52', 'age: 46', \n", " 'age: 58', 'age: 20', 'age: 39', 'age: 43', 'age: 31', 'age: 71', 'age: 49', \n", " 'age: 28', 'age: 29', 'age: 75', 'age: 74', 'age: 40', 'age: 59', 'age: 42', \n", " 'age: 35', 'age: 33'], \n", " 2: ['subject status/id: mixoid liposarcoma patient 1', 'subject status/id: mixoid liposarcoma patient 2', \n", " 'subject status/id: mixoid liposarcoma patient 3', 'subject status/id: mixoid liposarcoma patient 4', \n", " 'subject status/id: mixoid liposarcoma patient 5', 'subject status/id: mixoid liposarcoma patient 6', \n", " 'subject status/id: mixoid liposarcoma patient 7', 'subject status/id: mixoid liposarcoma patient 8', \n", " 'subject status/id: mixoid liposarcoma patient 9', 'subject status/id: mixoid liposarcoma patient 10', \n", " 'subject status/id: mixoid liposarcoma patient 11', 'subject status/id: mixoid liposarcoma patient 12', \n", " 'subject status/id: mixoid liposarcoma patient 13', 'subject status/id: mixoid liposarcoma patient 14', \n", " 'subject status/id: mixoid liposarcoma patient 15', 'subject status/id: mixoid liposarcoma patient 16', \n", " 'subject status/id: mixoid liposarcoma patient 17', 'subject status/id: mixoid liposarcoma patient 18', \n", " 'subject status/id: mixoid liposarcoma patient 19', 'subject status/id: mixoid liposarcoma patient 20', \n", " 'subject status/id: mixoid liposarcoma patient 21', 'subject status/id: mixoid liposarcoma patient 22', \n", " 'subject status/id: mixoid liposarcoma patient 23', 'subject status/id: mixoid liposarcoma patient 24', \n", " 'subject status/id: mixoid liposarcoma patient 25', 'subject status/id: mixoid liposarcoma patient 26', \n", " 'subject status/id: mixoid liposarcoma patient 27', 'subject status/id: mixoid liposarcoma patient 28', \n", " 'subject status/id: mixoid liposarcoma patient 29', 'subject status/id: mixoid liposarcoma patient 30'], \n", " 3: ['metastasis: 0', 'metastasis: 1'], \n", " 4: ['time_mfs: 9.78630136986301', 'time_mfs: 0.463013698630137', 'time_mfs: 13.9150684931507', \n", " 'time_mfs: 7.37534246575343', 'time_mfs: 11.9095890410959', 'time_mfs: 8.65753424657534', \n", " 'time_mfs: 8.10684931506849', 'time_mfs: 6.52054794520548', 'time_mfs: 7.06301369863014', \n", " 'time_mfs: 4.65753424657534', 'time_mfs: 6.75068493150685', 'time_mfs: 1.29315068493151', \n", " 'time_mfs: 4.33150684931507', 'time_mfs: 4.50958904109589', 'time_mfs: 2.83835616438356', \n", " 'time_mfs: 3.41917808219178', 'time_mfs: 1.70684931506849', 'time_mfs: 0.687671232876712', \n", " 'time_mfs: 0.520547945205479', 'time_mfs: 0.501369863013699', 'time_mfs: 0.476712328767123', \n", " 'time_mfs: 0.591780821917808', 'time_mfs: 0.441095890410959', 'time_mfs: 0.180821917808219', \n", " 'time_mfs: 0.0575342465753425', 'time_mfs: 0.747945205479452', 'time_mfs: 0.380821917808219\n" ] }, { "cell_type": "markdown", "id": "6b5829df", "metadata": {}, "source": [ "### Step 3: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "1d433786", "metadata": {}, "outputs": [], "source": [ "\n", "import os\n", "import pandas as pd\n", "import json\n", "import numpy as np\n", "import gzip\n", "from typing import Dict, Any, Optional, Callable\n", "\n", "# Function to read gzipped matrix file\n", "def read_gzipped_matrix(file_path):\n", " with gzip.open(file_path, 'rt') as f:\n", " lines = f.readlines()\n", " return lines\n", "\n", "# Load the matrix file (handling gzipped version)\n", "matrix_file = os.path.join(in_cohort_dir, f\"{cohort}_series_matrix.txt.gz\")\n", "if os.path.exists(matrix_file):\n", " # Read the gzipped file\n", " lines = read_gzipped_matrix(matrix_file)\n", " \n", " # Extract metadata section and data section\n", " metadata_lines = []\n", " data_start_idx = None\n", " for i, line in enumerate(lines):\n", " if line.startswith('!series_matrix_table_begin'):\n", " data_start_idx = i + 1\n", " break\n", " metadata_lines.append(line)\n", " \n", " # Extract sample characteristics\n", " sample_char_lines = [line for line in metadata_lines if line.startswith('!Sample_characteristics_ch1')]\n", " \n", " if sample_char_lines:\n", " # Parse sample characteristics into a dataframe\n", " sample_chars = []\n", " for line in sample_char_lines:\n", " parts = line.strip().split('\\t')\n", " sample_chars.append(parts[1:])\n", " \n", " clinical_data = pd.DataFrame(sample_chars)\n", " \n", " # Print unique values for each row to identify trait, age, and gender\n", " print(\"Examining sample characteristics rows:\")\n", " for i in range(len(clinical_data.index)):\n", " unique_values = clinical_data.iloc[i].unique()\n", " print(f\"Row {i} unique values: {unique_values}\")\n", " \n", " # Check if there's a gene expression data section\n", " if data_start_idx is not None:\n", " data_line = lines[data_start_idx].strip()\n", " data_cols = data_line.split('\\t')\n", " first_data_line = lines[data_start_idx + 1].strip().split('\\t')\n", " \n", " print(\"\\nFirst few data columns:\")\n", " for i in range(min(5, len(data_cols))):\n", " print(f\"{data_cols[i]}: {first_data_line[i] if i < len(first_data_line) else 'N/A'}\")\n", "else:\n", " print(f\"Matrix file {matrix_file} not found.\")\n", " clinical_data = pd.DataFrame()\n", "\n", "# 1. Gene Expression Data Availability\n", "# Check if there's data that looks like gene expression\n", "is_gene_available = True if data_start_idx is not None else False\n", "\n", "# 2.1 Data Availability\n", "# Based on the examination of the sample characteristics:\n", "# Row 0: Sex information\n", "# Row 1: Age information\n", "# Row 3: Metastasis status (binary, can be used as the trait)\n", "gender_row = 0 # Sex information\n", "age_row = 1 # Age information\n", "trait_row = 3 # Using metastasis status as the trait variable\n", "\n", "# Validate that these rows exist and contain useful data\n", "if len(clinical_data.index) <= trait_row or len(clinical_data.iloc[trait_row].unique()) <= 1:\n", " trait_row = None\n", "if len(clinical_data.index) <= age_row or len(clinical_data.iloc[age_row].unique()) <= 1:\n", " age_row = None\n", "if len(clinical_data.index) <= gender_row or len(clinical_data.iloc[gender_row].unique()) <= 1:\n", " gender_row = None\n", "\n", "# 2.2 Data Type Conversion Functions\n", "def convert_trait(value):\n", " if value is None or pd.isna(value):\n", " return None\n", " \n", " # Extract value after colon if present\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Convert metastasis status to binary\n", " value = value.strip('\"') # Remove quotes\n", " try:\n", " return int(value) # Already 0 or 1\n", " except:\n", " return None\n", "\n", "def convert_age(value):\n", " if value is None or pd.isna(value):\n", " return None\n", " \n", " # Extract value after colon if present\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Remove quotes\n", " value = value.strip('\"')\n", " \n", " # Try to extract numeric age\n", " import re\n", " age_match = re.search(r'\\d+', value)\n", " if age_match:\n", " return float(age_match.group())\n", " return None\n", "\n", "def convert_gender(value):\n", " if value is None or pd.isna(value):\n", " return None\n", " \n", " # Extract value after colon if present\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Remove quotes\n", " value = value.strip('\"')\n", " \n", " # Convert to binary (0: female, 1: male)\n", " lower_value = value.lower()\n", " if 'female' in lower_value or 'f' == lower_value:\n", " return 0\n", " elif 'male' in lower_value or 'm' == lower_value:\n", " return 1\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", " selected_clinical_df = geo_select_clinical_features(\n", " clinical_data, trait, trait_row, convert_trait,\n", " age_row, convert_age if age_row is not None else None,\n", " gender_row, convert_gender if gender_row is not None else None\n", " )\n", " \n", " # Preview the selected clinical features\n", " print(\"\\nPreview of selected clinical features:\")\n", " print(preview_df(selected_clinical_df))\n", " \n", " # Save 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)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n", "else:\n", " print(\"No trait data available, skipping clinical feature extraction.\")\n" ] }, { "cell_type": "markdown", "id": "1f2ef5c2", "metadata": {}, "source": [ "### Step 4: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "d86fca0d", "metadata": {}, "outputs": [], "source": [ "# 1. First get the path to the soft and matrix files\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# 2. Looking more carefully at the background information\n", "# This is a SuperSeries which doesn't contain direct gene expression data\n", "# Need to investigate the soft file to find the subseries\n", "print(\"This appears to be a SuperSeries. Looking at the SOFT file to find potential subseries:\")\n", "\n", "# Open the SOFT file to try to identify subseries\n", "with gzip.open(soft_file, 'rt') as f:\n", " subseries_lines = []\n", " for i, line in enumerate(f):\n", " if 'Series_relation' in line and 'SuperSeries of' in line:\n", " subseries_lines.append(line.strip())\n", " if i > 1000: # Limit search to first 1000 lines\n", " break\n", "\n", "# Display the subseries found\n", "if subseries_lines:\n", " print(\"Found potential subseries references:\")\n", " for line in subseries_lines:\n", " print(line)\n", "else:\n", " print(\"No subseries references found in the first 1000 lines of the SOFT file.\")\n", "\n", "# Despite trying to extract gene data, we expect it might fail because this is a SuperSeries\n", "try:\n", " gene_data = get_genetic_data(matrix_file)\n", " print(\"\\nGene data extraction result:\")\n", " print(\"Number of rows:\", len(gene_data))\n", " print(\"First 20 gene/probe identifiers:\")\n", " print(gene_data.index[:20])\n", "except Exception as e:\n", " print(f\"Error extracting gene data: {e}\")\n", " print(\"This confirms the dataset is a SuperSeries without direct gene expression data.\")\n" ] }, { "cell_type": "markdown", "id": "79892f51", "metadata": {}, "source": [ "### Step 5: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": null, "id": "023b5c28", "metadata": {}, "outputs": [], "source": [ "# Based on the gene identifiers shown, these don't appear to be standard human gene symbols\n", "# The identifiers (like A_23_P100001) look like Agilent microarray probe IDs\n", "# These will need to be mapped to standard gene symbols for proper analysis\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "d00c871c", "metadata": {}, "source": [ "### Step 6: Gene Annotation" ] }, { "cell_type": "code", "execution_count": null, "id": "7a37d789", "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": "f50215fe", "metadata": {}, "source": [ "### Step 7: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": null, "id": "b541020b", "metadata": {}, "outputs": [], "source": [ "# 1. Determine which columns contain gene identifiers and gene symbols\n", "# Looking at the gene annotation preview and gene expression data:\n", "# - 'ID' in gene_annotation contains probe identifiers (e.g., A_23_P100001)\n", "# - 'GENE_SYMBOL' contains human gene symbols (e.g., FAM174B)\n", "\n", "# 2. Extract the relevant columns for mapping\n", "probe_id_col = 'ID'\n", "gene_symbol_col = 'GENE_SYMBOL'\n", "\n", "gene_mapping = get_gene_mapping(gene_annotation, probe_id_col, gene_symbol_col)\n", "print(f\"Gene mapping dataframe shape: {gene_mapping.shape}\")\n", "print(\"First few rows of gene mapping:\")\n", "print(gene_mapping.head())\n", "\n", "# 3. Apply gene mapping to convert from probe-level to gene-level expression\n", "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n", "print(f\"Converted gene expression data shape: {gene_data.shape}\")\n", "print(\"First few rows of gene expression data:\")\n", "print(gene_data.head())\n", "\n", "# Normalize gene symbols\n", "gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"Final gene expression data shape after normalization: {gene_data.shape}\")\n", "print(\"First few rows after normalization:\")\n", "print(gene_data.head())\n", "\n", "# Save the 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": "1f2171f7", "metadata": {}, "source": [ "### Step 8: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": null, "id": "91b1e76e", "metadata": {}, "outputs": [], "source": [ "# 1. First, we'll reload the clinical data that was processed in Step 3\n", "# This contains the metastasis status, age, and gender information\n", "clinical_data = pd.read_csv(out_clinical_data_file, index_col=0)\n", "print(f\"Loaded clinical data from Step 3, shape: {clinical_data.shape}\")\n", "\n", "# If the current clinical data is just the \"Sarcoma\" variable, let's recreate it\n", "# based on the analysis we did in Step 3\n", "if clinical_data.shape[0] == 1 and \"Sarcoma\" in clinical_data.index:\n", " print(\"Recreating clinical data with metastasis, age, and gender...\")\n", " \n", " # Get the matrix file to extract the sample characteristics data\n", " soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", " \n", " # Get background info and clinical data from the matrix file\n", " background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']\n", " clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']\n", " background_info, clinical_raw = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n", " \n", " # Define the conversion functions from Step 3\n", " def convert_trait(value):\n", " if value is None or pd.isna(value):\n", " return None\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " value = value.strip('\"')\n", " try:\n", " return int(value) # Already 0 or 1\n", " except:\n", " return None\n", "\n", " def convert_age(value):\n", " if value is None or pd.isna(value):\n", " return None\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " value = value.strip('\"')\n", " import re\n", " age_match = re.search(r'\\d+', value)\n", " if age_match:\n", " return float(age_match.group())\n", " return None\n", "\n", " def convert_gender(value):\n", " if value is None or pd.isna(value):\n", " return None\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " value = value.strip('\"')\n", " lower_value = value.lower()\n", " if 'female' in lower_value or 'f' == lower_value:\n", " return 0\n", " elif 'male' in lower_value or 'm' == lower_value:\n", " return 1\n", " return None\n", " \n", " # Extract clinical features using the row indices identified in Step 3\n", " trait_row = 3 # Metastasis status\n", " age_row = 1 # Age information\n", " gender_row = 0 # Sex information\n", " \n", " # Use \"Metastasis\" as the trait name since we're using metastasis status\n", " trait_name = \"Metastasis\"\n", " \n", " clinical_data = geo_select_clinical_features(\n", " clinical_raw, trait_name, trait_row, convert_trait,\n", " age_row, convert_age, gender_row, convert_gender\n", " )\n", " \n", " # Save the updated clinical data\n", " clinical_data.to_csv(out_clinical_data_file)\n", " print(f\"Updated clinical data saved to {out_clinical_data_file}\")\n", " print(\"Clinical data sample:\")\n", " print(preview_df(clinical_data))\n", "\n", "print(f\"Clinical data shape: {clinical_data.shape}\")\n", "\n", "# 2. Load the gene expression data\n", "gene_data = pd.read_csv(out_gene_data_file, index_col=0)\n", "print(f\"Loaded gene expression data shape: {gene_data.shape}\")\n", "\n", "# 3. Link clinical and genetic data\n", "linked_data = geo_link_clinical_genetic_data(clinical_data, gene_data)\n", "print(f\"Shape of linked data: {linked_data.shape}\")\n", "print(\"Linked data sample (first 5 rows, 5 columns):\")\n", "print(linked_data.iloc[:5, :5])\n", "\n", "# 4. Handle missing values in the linked data\n", "# The trait variable is \"Metastasis\" (not \"Sarcoma\")\n", "trait_name = \"Metastasis\" if \"Metastasis\" in linked_data.columns else clinical_data.index[0]\n", "linked_data_cleaned = handle_missing_values(linked_data, trait_name)\n", "print(f\"Shape of linked data after handling missing values: {linked_data_cleaned.shape}\")\n", "\n", "# 5. Check if the trait and demographic features are biased\n", "is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data_cleaned, trait_name)\n", "\n", "# 6. Validate the dataset and save cohort information\n", "note = \"Dataset contains expression data for myxoid liposarcoma patients. Metastasis status (0=no metastasis, 1=metastasis) is used as the trait variable for association studies.\"\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=note\n", ")\n", "\n", "# 7. Save the linked data if it's usable\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\"Saved processed linked data to {out_data_file}\")\n", "else:\n", " print(\"Dataset validation failed. Final linked data not saved.\")" ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 5 }