{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "18594a00", "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 = \"Thyroid_Cancer\"\n", "cohort = \"GSE104005\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Thyroid_Cancer\"\n", "in_cohort_dir = \"../../input/GEO/Thyroid_Cancer/GSE104005\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Thyroid_Cancer/GSE104005.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Thyroid_Cancer/gene_data/GSE104005.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Thyroid_Cancer/clinical_data/GSE104005.csv\"\n", "json_path = \"../../output/preprocess/Thyroid_Cancer/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "49d8ef19", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": null, "id": "3b8643b9", "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": "b837e763", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "b28523b0", "metadata": {}, "outputs": [], "source": [ "# 1. Gene Expression Data Availability \n", "# Based on the series overall design, this dataset contains gene expression data using HumanHT-12 WG-DASL V4.0 R2 expression beadchip\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "# Trait data is available in row 0 - disease status\n", "trait_row = 0\n", "# Age data is available in row 2\n", "age_row = 2\n", "# Gender data is available in row 3 as Sex\n", "gender_row = 3\n", "\n", "# 2.2 Data Type Conversion Functions\n", "def convert_trait(value):\n", " \"\"\"Convert thyroid cancer status to binary: 1 for cancer, 0 for non-neoplastic.\"\"\"\n", " if value is None:\n", " return None\n", " # Extract value after colon if present\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " if 'Non-neoplastic' in value:\n", " return 0 # Control\n", " elif 'carcinoma' in value or 'Thyroid_carcinoma' in value:\n", " return 1 # Case\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age to continuous numeric value.\"\"\"\n", " if value is None:\n", " return None\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:\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender to binary: 0 for female, 1 for male.\"\"\"\n", " if value is None:\n", " return None\n", " # Extract value after colon if present\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " if value.upper() == 'F':\n", " return 0 # Female\n", " elif value.upper() == 'M':\n", " return 1 # Male\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", "validate_and_save_cohort_info(is_final=False, cohort=cohort, info_path=json_path, \n", " is_gene_available=is_gene_available, \n", " is_trait_available=is_trait_available)\n", "\n", "# 4. Clinical Feature Extraction\n", "if trait_row is not None:\n", " # Create a DataFrame from the Sample Characteristics Dictionary\n", " # We need to first transpose the data to make it compatible\n", " sample_chars = {\n", " 0: ['disease: Thyroid_carcinoma', 'disease: Non-neoplastic_thyroid'], \n", " 1: ['histology: PDTC', 'histology: PDTC+ATC', 'histology: PTC', 'histology: Non-neoplastic_thyroid', \n", " 'histology: PDTC+PTC', 'histology: PTC_lymph_node_metastasis', 'histology: PTC+PDTC'], \n", " 2: ['age: 74', 'age: 67', 'age: 72', 'age: 38', 'age: 50', 'age: 41', 'age: 51', 'age: 73', \n", " 'age: 52', 'age: 48', 'age: 59', 'age: 58', 'age: 39', 'age: 37', 'age: 33', 'age: 36', \n", " 'age: 70', 'age: 26', 'age: 46', 'age: 57', 'age: 44', 'age: 35', 'age: 42', 'age: 61', 'age: 49'], \n", " 3: ['Sex: M', 'Sex: F']\n", " }\n", " \n", " # Convert the dictionary to a DataFrame\n", " clinical_data = pd.DataFrame.from_dict(sample_chars, orient='index')\n", " \n", " # Extract clinical features\n", " clinical_df = 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", " # Preview the dataframe\n", " preview = preview_df(clinical_df)\n", " print(\"Clinical data preview:\")\n", " print(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 clinical data to CSV\n", " 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": "08afd035", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "702b7338", "metadata": {}, "outputs": [], "source": [ "# 1. Identify the paths to the SOFT file and the matrix file\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "print(f\"SOFT file: {soft_file}\")\n", "print(f\"Matrix file: {matrix_file}\")\n", "\n", "# Set gene availability flag\n", "is_gene_available = True # Initially assume gene data is available\n", "\n", "# First check if the matrix file contains the expected marker\n", "found_marker = False\n", "try:\n", " with gzip.open(matrix_file, 'rt') as file:\n", " for line in file:\n", " if \"!series_matrix_table_begin\" in line:\n", " found_marker = True\n", " break\n", " \n", " if found_marker:\n", " print(\"Found the matrix table marker in the file.\")\n", " else:\n", " print(\"Warning: Could not find '!series_matrix_table_begin' marker in the file.\")\n", " \n", " # Try to extract gene data from the matrix file\n", " gene_data = get_genetic_data(matrix_file)\n", " \n", " if gene_data.shape[0] == 0:\n", " print(\"Warning: Extracted gene data has 0 rows.\")\n", " is_gene_available = False\n", " else:\n", " print(f\"Gene data shape: {gene_data.shape}\")\n", " # Print the first 20 gene/probe identifiers\n", " print(\"First 20 gene/probe identifiers:\")\n", " print(gene_data.index[:20].tolist())\n", " \n", "except Exception as e:\n", " print(f\"Error extracting gene data: {e}\")\n", " is_gene_available = False\n", " \n", " # Try to diagnose the file format\n", " print(\"Examining file content to diagnose the issue:\")\n", " try:\n", " with gzip.open(matrix_file, 'rt') as file:\n", " for i, line in enumerate(file):\n", " if i < 10: # Print first 10 lines to diagnose\n", " print(f\"Line {i}: {line.strip()[:100]}...\") # Print first 100 chars of each line\n", " else:\n", " break\n", " except Exception as e2:\n", " print(f\"Error examining file: {e2}\")\n", "\n", "if not is_gene_available:\n", " print(\"Gene expression data could not be successfully extracted from this dataset.\")\n" ] }, { "cell_type": "markdown", "id": "4e97dac3", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": null, "id": "3dd6a95e", "metadata": {}, "outputs": [], "source": [ "# Analyze the gene identifiers starting with \"ILMN_\"\n", "# These are Illumina BeadArray probe IDs, not human gene symbols\n", "# They need to be mapped to standard gene symbols for analysis\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "e814ab9a", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": null, "id": "c83c2919", "metadata": {}, "outputs": [], "source": [ "# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "gene_annotation = get_gene_annotation(soft_file)\n", "\n", "# 2. Analyze the gene annotation dataframe to identify which columns contain the gene identifiers and gene symbols\n", "print(\"\\nGene annotation preview:\")\n", "print(f\"Columns in gene annotation: {gene_annotation.columns.tolist()}\")\n", "print(preview_df(gene_annotation, n=5))\n", "\n", "# Get a more complete view to understand the annotation structure\n", "print(\"\\nComplete sample of a few rows:\")\n", "print(gene_annotation.iloc[:3, :4].to_string()) # Show only first few columns for readability\n", "\n", "# Examine the Symbol column which contains gene information\n", "print(\"\\nChecking for gene information in Symbol column:\")\n", "if 'Symbol' in gene_annotation.columns:\n", " sample_symbols = gene_annotation['Symbol'].head(5).tolist()\n", " print(f\"Sample Symbol values: {sample_symbols}\")\n", " \n", " # Use the library function to create the mapping\n", " mapping_data = get_gene_mapping(gene_annotation, 'ID', 'Symbol')\n", " \n", " # Print sample of the mapping to confirm\n", " print(\"\\nSample of probe ID to gene symbol mappings:\")\n", " print(mapping_data.head(10))\n", " \n", " # Check the size of the mapping data\n", " print(f\"\\nTotal number of probe-to-gene mappings: {len(mapping_data)}\")\n", " \n", " # Check how many unique gene symbols we have\n", " unique_genes = mapping_data['Gene'].nunique()\n", " print(f\"Number of unique gene symbols: {unique_genes}\")\n", "else:\n", " print(\"\\nError: Could not find 'Symbol' column in the annotation data\")\n" ] }, { "cell_type": "markdown", "id": "d3d34d73", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": null, "id": "b52ca165", "metadata": {}, "outputs": [], "source": [ "# 1. Analyze gene identifiers in gene expression data and gene annotation data\n", "# In the gene expression data, the identifiers start with ILMN_ (like ILMN_1343291)\n", "# In the gene annotation data, these are in the 'ID' column\n", "# Gene symbols are in the 'Symbol' column\n", "\n", "# 2. Extract gene mapping from annotation data\n", "# We need to map from probe IDs to gene symbols\n", "mapping_df = get_gene_mapping(gene_annotation, 'ID', 'Symbol')\n", "print(f\"Created mapping dataframe with {len(mapping_df)} rows\")\n", "\n", "# 3. Apply gene mapping to convert probe-level measurements to gene expression data\n", "# This handles the many-to-many relation between probes and genes as specified\n", "gene_data = apply_gene_mapping(gene_data, mapping_df)\n", "print(f\"Mapped gene expression data shape: {gene_data.shape}\")\n", "print(\"First 10 gene symbols in the mapped data:\")\n", "print(gene_data.index[:10].tolist())\n", "\n", "# To check if we have actual human gene symbols\n", "human_genes = gene_data.index[gene_data.index.str.match(r'[A-Z0-9]{1,10}')].tolist()[:10]\n", "print(f\"\\nSample human gene symbols: {human_genes}\")\n", "\n", "# Save the gene expression 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\"Gene expression data saved to {out_gene_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "d47ba024", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": null, "id": "a0e0d9bc", "metadata": {}, "outputs": [], "source": [ "```python\n", "# 1. Normalize gene symbols in the gene expression data\n", "try:\n", " # Make sure the directory exists\n", " os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", " \n", " # Use the gene_data variable from the previous step (don't try to load it from file)\n", " print(f\"Gene data shape before normalization: {gene_data.shape}\")\n", " \n", " # Apply normalization to gene symbols\n", " normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", " print(f\"Gene data shape after normalization: {normalized_gene_data.shape}\")\n", " \n", " # Save the normalized gene data\n", " normalized_gene_data.to_csv(out_gene_data_file)\n", " print(f\"Normalized gene data saved to {out_gene_data_file}\")\n", " \n", " # Use the normalized data for further processing\n", " gene_data = normalized_gene_data\n", " is_gene_available = True\n", "except Exception as e:\n", " print(f\"Error normalizing gene data: {e}\")\n", " is_gene_available = False\n", "\n", "# 2. Load clinical data\n", "try:\n", " # Load the clinical data from file\n", " clinical_data = pd.read_csv(out_clinical_data_file)\n", " print(f\"Loaded clinical data shape: {clinical_data.shape}\")\n", " is_trait_available = True\n", "except Exception as e:\n", " print(f\"Error loading clinical data: {e}\")\n", " # Reload the clinical data directly from the matrix file\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 with correct indices from Step 2\n", " clinical_features = geo_select_clinical_features(\n", " clinical_df=clinical_data,\n", " trait=trait,\n", " trait_row=0, # Correct trait row from Step 2\n", " convert_trait=convert_trait,\n", " gender_row=3, # Correct gender row from Step 2\n", " convert_gender=convert_gender,\n", " age_row=2, # Age row from Step 2\n", " convert_age=convert_age\n", " )\n", " \n", " print(f\"Re-extracted clinical data shape: {clinical_features.shape}\")\n", " print(\"Preview of clinical data (first 5 samples):\")\n", " print(clinical_features.head())\n", " \n", " # Save the properly extracted 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", " clinical_data = clinical_features\n", " is_trait_available = True\n", "\n", "# 3. Link clinical and genetic data if both are available\n", "if is_trait_available and is_gene_available:\n", " try:\n", " # Transpose the clinical data if needed to have the same format as gene data\n", " if isinstance(clinical_data, pd.DataFrame) and clinical_data.shape[0] <= 3:\n", " clinical_data = clinical_data.T\n", " clinical_data.columns = [trait, 'Age', 'Gender']\n", " \n", " # Debug column comparison to ensure compatibility\n", " gene_sample_ids = set(gene_data.columns)\n", " clinical_sample_ids = set(clinical_data.index)\n", " common_samples = gene_sample_ids.intersection(clinical_sample_ids)\n", " print(f\"Found {len(common_samples)} common samples between gene and clinical data\")\n", " \n", " if len(common_samples) > 0:\n", " # Select only common samples from both datasets\n", " gene_data_filtered = gene_data[list(common_samples)]\n", " clinical_data_filtered = clinical_data.loc[list(common_samples)]\n", " \n", " # Create linked data\n", " linked_data = pd.DataFrame(index=clinical_data_filtered.index)\n", " \n", " # Add clinical features\n", " if trait in clinical_data_filtered.columns:\n", " linked_data[trait] = clinical_data_filtered[trait]\n", " if 'Age' in clinical_data_filtered.columns:\n", " linked_data['Age'] = clinical_data_filtered['Age']\n", " if 'Gender' in clinical_data_filtered.columns:\n", " linked_data['Gender'] = clinical_data_filtered['Gender']\n", " \n", " # Add gene features - transpose so genes are columns\n", " gene_data_filtered_T = gene_data_filtered.T\n", " for gene in gene_data_filtered.index:\n", " linked_data[gene] = gene_data_filtered_T[gene]\n", " \n", " print(f\"Initial linked data shape: {linked_data.shape}\")\n", " print(\"Preview of linked data (first 5 rows, first 5 columns):\")\n", " print(linked_data.iloc[:5, :5])\n", " \n", " # Check if trait column exists and is not all NaN\n", " if trait in linked_data.columns and not linked_data[trait].isna().all():\n", " # 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", " if linked_data.shape[0] > 0:\n", " # Check for bias in trait and demographic features\n", " is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n", " \n", " # Validate the data quality and save cohort info\n", " note = \"Dataset contains gene expression data from thyroid cancer samples with tumor type 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=is_gene_available,\n", " is_trait_available=is_trait_available,\n", " is_biased=is_biased,\n", " df=linked_data,\n", " note=note\n", " )\n", " \n", " # 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", " linked_data.to_csv(out_data_file)\n", " print(f\"Linked data saved to {out_data_file}\")\n", " else:\n", " print(\"Data not usable for the trait study - not saving final linked data.\")\n", " else:\n", " print(\"After handling missing values, no samples remain.\")\n", " validate_and_save_cohort_info(\n", " is_final=True,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=is_gene_available,\n", " is_trait_available=is_trait_available,\n", " is_biased=True,\n", " df=pd.DataFrame(),\n", " note=\"No valid samples after handling missing values.\"\n", " )\n", " else:\n", " print(f\"Trait column '{trait}' missing or all values are NaN.\")\n", " validate_and_save_cohort_info(\n", " is_final=True,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=is_gene_available,\n", " is_trait_available=False,\n", " is_biased=True,\n", " df=linked_data,\n", " note=f\"Trait column '{trait}' missing or contains only NaN values.\"\n", " )\n", " else:\n", " print(\"No common samples found between gene expression and clinical data.\")\n", " validate_and_save_cohort_info(\n", " is_final=True,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=is_gene_available,\n", " is_trait_available=is_trait_available,\n", " is_biased=True,\n", " df=pd.DataFrame(),\n", " note=\"No common samples between gene expression and clinical data.\"\n", " )\n", " except Exception as e:\n", " print(f\"Error linking or processing data: {e}\")\n", " import traceback\n", " traceback.print_exc()\n", " validate_and_save_cohort_info(\n", " is_final=True,\n", " cohort=cohort\n" ] }, { "cell_type": "markdown", "id": "18522eb7", "metadata": {}, "source": [ "### Step 8: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": null, "id": "2c27670b", "metadata": {}, "outputs": [], "source": [ "```python\n", "# 1. Normalize gene symbols in the gene expression data\n", "try:\n", " # First reload the gene expression data from the matrix file\n", " soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", " gene_data = get_genetic_data(matrix_file)\n", " print(f\"Reloaded gene data shape: {gene_data.shape}\")\n", " \n", " # We need the gene annotation for mapping\n", " gene_annotation = get_gene_annotation(soft_file)\n", " mapping_df = get_gene_mapping(gene_annotation, 'ID', 'Symbol')\n", " gene_data = apply_gene_mapping(gene_data, mapping_df)\n", " print(f\"Mapped gene data shape: {gene_data.shape}\")\n", " \n", " # Make sure the directory exists\n", " os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", " \n", " # Apply normalization to gene symbols\n", " normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", " print(f\"Gene data shape after normalization: {normalized_gene_data.shape}\")\n", " \n", " # Save the normalized gene data\n", " normalized_gene_data.to_csv(out_gene_data_file)\n", " print(f\"Normalized gene data saved to {out_gene_data_file}\")\n", " \n", " # Use the normalized data for further processing\n", " gene_data = normalized_gene_data\n", " is_gene_available = True\n", "except Exception as e:\n", " print(f\"Error normalizing gene data: {e}\")\n", " is_gene_available = False\n", "\n", "# Redefine conversion functions from Step 2\n", "def convert_trait(value):\n", " \"\"\"Convert thyroid cancer status to binary: 1 for cancer, 0 for non-neoplastic.\"\"\"\n", " if value is None:\n", " return None\n", " # Extract value after colon if present\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " if 'Non-neoplastic' in value:\n", " return 0 # Control\n", " elif 'carcinoma' in value or 'Thyroid_carcinoma' in value:\n", " return 1 # Case\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age to continuous numeric value.\"\"\"\n", " if value is None:\n", " return None\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:\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender to binary: 0 for female, 1 for male.\"\"\"\n", " if value is None:\n", " return None\n", " # Extract value after colon if present\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " if value.upper() == 'F':\n", " return 0 # Female\n", " elif value.upper() == 'M':\n", " return 1 # Male\n", " return None\n", "\n", "# 2. Load clinical data and extract features\n", "try:\n", " # Load the clinical data from file\n", " background_info, clinical_data = get_background_and_clinical_data(matrix_file)\n", " \n", " # Extract clinical features with CORRECT indices from Step 2\n", " clinical_features = geo_select_clinical_features(\n", " clinical_df=clinical_data,\n", " trait=trait,\n", " trait_row=0, # Disease status (Thyroid_carcinoma vs Non-neoplastic)\n", " convert_trait=convert_trait,\n", " gender_row=3, # Sex row\n", " convert_gender=convert_gender,\n", " age_row=2, # Age row\n", " convert_age=convert_age\n", " )\n", " \n", " print(f\"Extracted clinical data shape: {clinical_features.shape}\")\n", " print(\"Preview of clinical data (first 5 samples):\")\n", " print(clinical_features.iloc[:, :5])\n", " \n", " # Save the properly extracted 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", " is_trait_available = True\n", "except Exception as e:\n", " print(f\"Error extracting clinical data: {e}\")\n", " is_trait_available = False\n", "\n", "# 3. Link clinical and genetic data if both are available\n", "if is_trait_available and is_gene_available:\n", " try:\n", " # Check for common sample IDs\n", " common_samples = set(gene_data.columns).intersection(clinical_features.columns)\n", " print(f\"Found {len(common_samples)} common samples between gene and clinical data\")\n", " \n", " if len(common_samples) > 0:\n", " # Link the clinical and genetic data\n", " linked_data = geo_link_clinical_genetic_data(clinical_features, gene_data)\n", " print(f\"Initial linked data shape: {linked_data.shape}\")\n", " \n", " # Debug the trait values before handling missing values\n", " print(\"Preview of linked data (first 5 rows, first 5 columns):\")\n", " print(linked_data.iloc[:5, :5])\n", " \n", " # 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", " if linked_data.shape[0] > 0:\n", " # Check for bias in trait and demographic features\n", " is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n", " \n", " # Validate the data quality and save cohort info\n", " note = \"Dataset contains gene expression data from thyroid cancer samples with tumor type 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=is_gene_available,\n", " is_trait_available=is_trait_available,\n", " is_biased=is_biased,\n", " df=linked_data,\n", " note=note\n", " )\n", " \n", " # 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", " linked_data.to_csv(out_data_file)\n", " print(f\"Linked data saved to {out_data_file}\")\n", " else:\n", " print(\"Data not usable for the trait study - not saving final linked data.\")\n", " else:\n", " print(\"After handling missing values, no samples remain.\")\n", " validate_and_save_cohort_info(\n", " is_final=True,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=is_gene_available,\n", " is_trait_available=is_trait_available,\n", " is_biased=True,\n", " df=pd.DataFrame(),\n", " note=\"No valid samples after handling missing values.\"\n", " )\n", " else:\n", " print(\"No common samples found between gene expression and clinical data.\")\n", " validate_and_save_cohort_info(\n", " is_final=True,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=is_gene_available,\n", " is_trait_available=is_trait_available,\n", " is_biased=True,\n", " df=pd.DataFrame(),\n", " note=\"No common samples between gene expression and clinical data.\"\n", " )\n", " except Exception as e:\n", " print(f\"Error linking or processing data: {e}\")\n", " import traceback\n", " traceback.print_exc()\n", " validate_and_save_cohort_info(\n", " is_final=True,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=is_gene_available,\n", " is_trait_available=is_trait_available,\n", " is_biased=True, # Assume biased if there's an error\n", " df=pd.DataFrame(), # Empty dataframe for metadata\n", " note=f\"Error in data processing: {str(e)}\"\n" ] }, { "cell_type": "markdown", "id": "55dac307", "metadata": {}, "source": [ "### Step 9: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": null, "id": "4e7f234e", "metadata": {}, "outputs": [], "source": [ "# 1. Normalize gene symbols in the gene expression data\n", "try:\n", " # Make sure the directory exists\n", " os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", " \n", " # Use the gene_data variable from the previous step (don't try to load it from file)\n", " print(f\"Gene data shape before normalization: {gene_data.shape}\")\n", " \n", " # Apply normalization to gene symbols\n", " normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", " print(f\"Gene data shape after normalization: {normalized_gene_data.shape}\")\n", " \n", " # Save the normalized gene data\n", " normalized_gene_data.to_csv(out_gene_data_file)\n", " print(f\"Normalized gene data saved to {out_gene_data_file}\")\n", " \n", " # Use the normalized data for further processing\n", " gene_data = normalized_gene_data\n", " is_gene_available = True\n", "except Exception as e:\n", " print(f\"Error normalizing gene data: {e}\")\n", " is_gene_available = False\n", "\n", "# 2. Load clinical data\n", "try:\n", " # Load the clinical data from file\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", " # Debug the trait and gender conversion functions\n", " print(\"Sample conversion results:\")\n", " sample_trait = list(clinical_data.iloc[2])[1] # Get a sample from trait row (row 2)\n", " sample_gender = list(clinical_data.iloc[0])[1] # Get a sample from gender row (row 0)\n", " print(f\"Sample trait value: '{sample_trait}' -> {convert_trait(sample_trait)}\")\n", " print(f\"Sample gender value: '{sample_gender}' -> {convert_gender(sample_gender)}\")\n", " \n", " # Extract clinical features with CORRECT indices from Step 2\n", " clinical_features = geo_select_clinical_features(\n", " clinical_df=clinical_data,\n", " trait=trait,\n", " trait_row=2, # Correct trait row from Step 2\n", " convert_trait=convert_trait,\n", " gender_row=0, # Correct gender row from Step 2\n", " convert_gender=convert_gender,\n", " age_row=None, # Age row is None as per Step 2\n", " convert_age=None\n", " )\n", " \n", " print(f\"Extracted clinical data shape: {clinical_features.shape}\")\n", " print(\"Preview of clinical data (first 5 samples):\")\n", " print(clinical_features.iloc[:, :5])\n", " \n", " # Save the properly extracted 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", " is_trait_available = True\n", "except Exception as e:\n", " print(f\"Error extracting clinical data: {e}\")\n", " is_trait_available = False\n", "\n", "# 3. Link clinical and genetic data if both are available\n", "if is_trait_available and is_gene_available:\n", " try:\n", " # Debug the column names to ensure they match\n", " print(f\"Gene data columns (first 5): {gene_data.columns[:5].tolist()}\")\n", " print(f\"Clinical data columns (first 5): {clinical_features.columns[:5].tolist()}\")\n", " \n", " # Check for common sample IDs\n", " common_samples = set(gene_data.columns).intersection(clinical_features.columns)\n", " print(f\"Found {len(common_samples)} common samples between gene and clinical data\")\n", " \n", " if len(common_samples) > 0:\n", " # Link the clinical and genetic data\n", " linked_data = geo_link_clinical_genetic_data(clinical_features, gene_data)\n", " print(f\"Initial linked data shape: {linked_data.shape}\")\n", " \n", " # Debug the trait values before handling missing values\n", " print(\"Preview of linked data (first 5 rows, first 5 columns):\")\n", " print(linked_data.iloc[:5, :5])\n", " \n", " # 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", " if linked_data.shape[0] > 0:\n", " # Check for bias in trait and demographic features\n", " is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n", " \n", " # Validate the data quality and save cohort info\n", " note = \"Dataset contains gene expression data from thyroid cancer samples with tumor type 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=is_gene_available,\n", " is_trait_available=is_trait_available,\n", " is_biased=is_biased,\n", " df=linked_data,\n", " note=note\n", " )\n", " \n", " # 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", " linked_data.to_csv(out_data_file)\n", " print(f\"Linked data saved to {out_data_file}\")\n", " else:\n", " print(\"Data not usable for the trait study - not saving final linked data.\")\n", " else:\n", " print(\"After handling missing values, no samples remain.\")\n", " validate_and_save_cohort_info(\n", " is_final=True,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=is_gene_available,\n", " is_trait_available=is_trait_available,\n", " is_biased=True,\n", " df=pd.DataFrame(),\n", " note=\"No valid samples after handling missing values.\"\n", " )\n", " else:\n", " print(\"No common samples found between gene expression and clinical data.\")\n", " validate_and_save_cohort_info(\n", " is_final=True,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=is_gene_available,\n", " is_trait_available=is_trait_available,\n", " is_biased=True,\n", " df=pd.DataFrame(),\n", " note=\"No common samples between gene expression and clinical data.\"\n", " )\n", " except Exception as e:\n", " print(f\"Error linking or processing data: {e}\")\n", " validate_and_save_cohort_info(\n", " is_final=True,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=is_gene_available,\n", " is_trait_available=is_trait_available,\n", " is_biased=True, # Assume biased if there's an error\n", " df=pd.DataFrame(), # Empty dataframe for metadata\n", " note=f\"Error in data processing: {str(e)}\"\n", " )\n", "else:\n", " # We can't proceed with linking if either trait or gene data is missing\n", " print(\"Cannot proceed with data linking due to missing trait or gene data.\")\n", " validate_and_save_cohort_info(\n", " is_final=True,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=is_gene_available,\n", " is_trait_available=is_trait_available,\n", " is_biased=True, # Data is unusable if we're missing components\n", " df=pd.DataFrame(), # Empty dataframe for metadata\n", " note=\"Missing essential data components for linking (trait data or gene expression data).\"\n", " )" ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 5 }