{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "5728adab", "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 = \"Arrhythmia\"\n", "cohort = \"GSE53622\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Arrhythmia\"\n", "in_cohort_dir = \"../../input/GEO/Arrhythmia/GSE53622\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Arrhythmia/GSE53622.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Arrhythmia/gene_data/GSE53622.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Arrhythmia/clinical_data/GSE53622.csv\"\n", "json_path = \"../../output/preprocess/Arrhythmia/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "8e0eab6e", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": null, "id": "f5eec03c", "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": "2dc4220d", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "d6ad9df0", "metadata": {}, "outputs": [], "source": [ "I'll provide the correct solution for step 2:\n", "\n", "```python\n", "# 1. Gene Expression Data Analysis\n", "# Based on the background information, this dataset contains lncRNA expression profiles, not typical gene expression.\n", "is_gene_available = False\n", "\n", "# 2. Data Availability and Type Conversion\n", "# 2.1 Data Availability\n", "\n", "# Trait data - Arrhythmia\n", "trait_row = 10 # 'arrhythmia: no', 'arrhythmia: yes'\n", "\n", "# Age data \n", "age_row = 1 # 'age: 66.4602739726027', etc.\n", "\n", "# Gender data\n", "gender_row = 2 # 'Sex: female', 'Sex: male'\n", "\n", "# 2.2 Data Type Conversion Functions\n", "\n", "def convert_trait(value):\n", " \"\"\"Convert arrhythmia status to binary values.\"\"\"\n", " if value is None:\n", " return None\n", " \n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip().lower()\n", " \n", " if value == \"yes\":\n", " return 1\n", " elif value == \"no\":\n", " return 0\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age to a continuous numeric value.\"\"\"\n", " if value is None:\n", " return None\n", " \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):\n", " \"\"\"Convert gender to binary (0: female, 1: male).\"\"\"\n", " if value is None:\n", " return None\n", " \n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip().lower()\n", " \n", " if value == \"female\":\n", " return 0\n", " elif value == \"male\":\n", " return 1\n", " else:\n", " return None\n", "\n", "# 3. Save metadata for initial filtering\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", " # Create a DataFrame from the sample characteristics dictionary\n", " sample_characteristics_dict = {\n", " 0: ['patient id: ec302', 'patient id: ec303', 'patient id: ec305', 'patient id: ec306', 'patient id: ec325', 'patient id: ec326', 'patient id: ec330', 'patient id: ec331', 'patient id: ec308', 'patient id: ec309', 'patient id: ec311', 'patient id: ec312', 'patient id: ec315', 'patient id: ec316', 'patient id: ec317', 'patient id: ec318', 'patient id: ec319', 'patient id: ec321', 'patient id: ec322', 'patient id: ec324', 'patient id: ec333', 'patient id: ec334', 'patient id: ec337', 'patient id: ec338', 'patient id: ec340', 'patient id: ec341', 'patient id: ec342', 'patient id: ec347', 'patient id: ec353', 'patient id: ec355'],\n", " 1: ['age: 66.4602739726027', 'age: 64.013698630137', 'age: 50.9123287671233', 'age: 46.3287671232877', 'age: 53.9972602739726', 'age: 67.8438356164384', 'age: 64.8794520547945', 'age: 45.2219178082192', 'age: 54.4794520547945', 'age: 56.2328767123288', 'age: 57.0986301369863', 'age: 44.6630136986301', 'age: 43.7698630136986', 'age: 67.2739726027397', 'age: 68.2904109589041', 'age: 60.5068493150685', 'age: 48.4027397260274', 'age: 54.2931506849315', 'age: 51.9890410958904', 'age: 58.3205479452055', 'age: 66.2712328767123', 'age: 72.241095890411', 'age: 64.7506849315069', 'age: 54.5753424657534', 'age: 62.4383561643836', 'age: 66.1479452054794', 'age: 53.7424657534247', 'age: 56.9643835616438', 'age: 71.9150684931507', 'age: 53.5643835616438'],\n", " 2: ['Sex: female', 'Sex: male'],\n", " 3: ['tobacco use: no', 'tobacco use: yes'],\n", " 4: ['alcohol use: no', 'alcohol use: yes'],\n", " 5: ['tumor loation: middle', 'tumor loation: lower', 'tumor loation: upper'],\n", " 6: ['tumor grade: moderately', 'tumor grade: poorly', 'tumor grade: well'],\n", " 7: ['t stage: T3', 't stage: T1', 't stage: T2', 't stage: T4'],\n", " 8: ['n stage: N2', 'n stage: N0', 'n stage: N1', 'n stage: N3'],\n", " 9: ['tnm stage: III', 'tnm stage: II', 'tnm stage: I'],\n", " 10: ['arrhythmia: no', 'arrhythmia: yes'],\n", " 11: ['pneumonia: no', 'pneumonia: yes'],\n", " 12: ['anastomotic leak: no', 'anastomotic leak: yes'],\n", " 13: ['adjuvant therapy: yes', 'adjuvant therapy: no', 'adjuvant therapy: unknown'],\n", " 14: ['death at fu: yes', 'death at fu: no'],\n", " 15: ['survival time(months): 11.6333333333333', 'survival time(months): 58.2', 'survival time(months): 39.1666666666667', 'survival time(months): 57.7333333333333', 'survival time(months): 11.0666666666667', 'survival time(months): 55.2666666666667', 'survival time(months): 29.7', 'survival time(months): 10.9666666666667', 'survival time(months): 57.6', 'survival time(months): 57.5333333333333', 'survival time(months): 57.3666666666667', 'survival time(months): 57.2666666666667', 'survival time(months): 57.2333333333333', 'survival time(months): 13', 'survival time(months): 5.7', 'survival time(months): 56.6333333333333', 'survival time(months): 56.1333333333333', 'survival time(months): 55.6666666666667', 'survival time(months): 6.26666666666667', 'survival time(months): 25.4666666666667', 'survival time(months): 10.2', 'survival time(months): 13.1666666666667', 'survival time(months): 54.7333333333333', 'survival time(months): 18.0666666666667', 'survival time(months): 36.3', 'survival time(months): 54.1', 'survival time(months): 16.0333333333333', 'survival time(months): 52.9333333333333', 'survival time(months): 52.7', 'survival time(months): 8.46666666666667'],\n", " 16: ['disease state: esophageal squamous cell carcinoma'],\n", " 17: ['tissue: cancer tissue from patient 302', 'tissue: normal tissue from patient 302', 'tissue: cancer tissue from patient 303', 'tissue: normal tissue from patient 303', 'tissue: cancer tissue\n" ] }, { "cell_type": "markdown", "id": "c05abbb2", "metadata": {}, "source": [ "### Step 3: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "2ecca341", "metadata": {}, "outputs": [], "source": [ "I've analyzed the error and will provide a fixed and complete solution:\n", "\n", "```python\n", "import pandas as pd\n", "import os\n", "import json\n", "import numpy as np\n", "import re\n", "import glob\n", "from typing import Dict, Any, Optional, Callable\n", "\n", "# --- Step 1: Explore available files in the directory\n", "available_files = glob.glob(os.path.join(in_cohort_dir, \"*\"))\n", "print(f\"Available files in {in_cohort_dir}:\")\n", "for file in available_files:\n", " print(f\" - {os.path.basename(file)}\")\n", "\n", "# Look for potential series matrix files with different patterns\n", "series_files = [f for f in available_files if \"series_matrix\" in f.lower() or \"series\" in f.lower()]\n", "if not series_files:\n", " # Try to find any text files\n", " series_files = [f for f in available_files if f.endswith('.txt') or f.endswith('.csv')]\n", "\n", "if not series_files:\n", " print(\"No suitable data files found. Cannot proceed with analysis.\")\n", " # If we have any files, let's try to examine the content of the first one\n", " if available_files:\n", " sample_file = available_files[0]\n", " print(f\"Examining content of {os.path.basename(sample_file)}:\")\n", " try:\n", " with open(sample_file, 'r') as f:\n", " content_preview = [next(f) for _ in range(min(10, os.path.getsize(sample_file)))]\n", " for line in content_preview:\n", " print(line.strip())\n", " except Exception as e:\n", " print(f\"Could not read file: {e}\")\n", " \n", " # Set variables to indicate data is not available\n", " is_gene_available = False\n", " is_trait_available = False\n", "else:\n", " # Use the first found file\n", " matrix_file_path = series_files[0]\n", " print(f\"Using file: {os.path.basename(matrix_file_path)}\")\n", " \n", " # Attempt to extract information from the file\n", " try:\n", " # Read file content\n", " with open(matrix_file_path, 'r') as file:\n", " # Read the first several lines to analyze header info\n", " header_lines = []\n", " line_count = 0\n", " max_lines = 200 # Read more lines to ensure we capture sample characteristics\n", " \n", " for line in file:\n", " header_lines.append(line)\n", " line_count += 1\n", " if line_count >= max_lines:\n", " break\n", " \n", " # Check if this is likely gene expression data\n", " platform_line = [line for line in header_lines if \"!Series_platform_id\" in line]\n", " is_gene_available = True\n", " \n", " if platform_line:\n", " platform_id = platform_line[0].split(\"=\")[1].strip().strip('\"')\n", " print(f\"Platform ID: {platform_id}\")\n", " # Check if platform suggests miRNA or methylation data\n", " if \"mirna\" in platform_id.lower() or \"methylation\" in platform_id.lower():\n", " print(\"Dataset appears to be miRNA or methylation data, not gene expression.\")\n", " is_gene_available = False\n", " \n", " # Extract sample characteristics\n", " sample_characteristics = {}\n", " for i, line in enumerate(header_lines):\n", " if line.startswith(\"!Sample_characteristics_ch1\"):\n", " parts = line.strip().split('\\t')\n", " if len(parts) > 1:\n", " if i not in sample_characteristics:\n", " sample_characteristics[i] = []\n", " for part in parts[1:]:\n", " sample_characteristics[i].append(part)\n", " \n", " # Check if sample characteristics were found\n", " if not sample_characteristics:\n", " print(\"No sample characteristics found in the file.\")\n", " for i, line in enumerate(header_lines[:20]):\n", " print(f\"Line {i}: {line.strip()}\")\n", " is_trait_available = False\n", " else:\n", " # Print unique values for each row to help identify variables\n", " print(\"\\nSample characteristics analysis:\")\n", " for key, values in sample_characteristics.items():\n", " unique_values = list(set(values))\n", " print(f\"Row {key}: {unique_values[:5]}\")\n", " if len(unique_values) > 5:\n", " print(f\" ...and {len(unique_values)-5} more unique values\")\n", " \n", " # Load clinical data\n", " clinical_data = pd.DataFrame()\n", " for key, values in sample_characteristics.items():\n", " clinical_data[key] = values\n", " \n", " # Based on inspection of sample characteristics, identify rows for trait, age, and gender\n", " trait_row = None\n", " age_row = None\n", " gender_row = None\n", " \n", " # Look for row containing Arrhythmia information\n", " for key, values in sample_characteristics.items():\n", " unique_str = ' '.join(set([str(v).lower() for v in values]))\n", " \n", " # Check for trait information (Arrhythmia)\n", " if any(term in unique_str for term in ['arrhythmia', 'disease', 'condition', 'patient', 'control', 'case']):\n", " trait_row = key\n", " print(f\"Found potential trait information in row {key}: {list(set(values))[:5]}\")\n", " \n", " # Check for age information\n", " if any(term in unique_str for term in ['age', 'years']):\n", " age_row = key\n", " print(f\"Found potential age information in row {key}: {list(set(values))[:5]}\")\n", " \n", " # Check for gender information\n", " if any(term in unique_str for term in ['gender', 'sex', 'male', 'female']):\n", " gender_row = key\n", " print(f\"Found potential gender information in row {key}: {list(set(values))[:5]}\")\n", " \n", " # Define conversion functions based on the identified data\n", " def convert_trait(value):\n", " \"\"\"Convert trait values to binary (0/1)\"\"\"\n", " if value is None or pd.isna(value):\n", " return None\n", " value = str(value).lower()\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Adapt based on the actual values in the dataset\n", " if any(term in value for term in ['control', 'normal', 'healthy', 'no', 'negative']):\n", " return 0\n", " elif any(term in value for term in ['arrhythmia', 'disease', 'patient', 'yes', 'positive']):\n", " return 1\n", " else:\n", " return None\n", " \n", " def convert_age(value):\n", " \"\"\"Convert age values to continuous numeric form\"\"\"\n", " if value is None or pd.isna(value):\n", " return None\n", " value = str(value)\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Extract numeric age using regex\n", " age_match = re.search(r'(\\d+)', value)\n", " if age_match:\n", " return float(age_match.group(1))\n", " else:\n", " return None\n", " \n", " def convert_gender(value):\n", " \"\"\"Convert gender values to binary (0 for female, 1 for male)\"\"\"\n", " if value is None or pd.isna(value):\n", " return None\n", " value = str(value).lower()\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " if any(term in value for term in ['female', 'f']):\n", " return 0\n", " elif any(term in value for term in ['male', 'm']):\n", " return 1\n", " else:\n", " return None\n", " \n", " is_trait_available = trait_row is not None\n", " \n", " # Save metadata for 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", " # Extract clinical features if trait data is available\n", " if is_trait_available:\n", " selected_clinical_df = geo_select_clinical_features(\n", " clinical_df=clinical_data,\n", " trait=trait,\n", " trait_\n" ] }, { "cell_type": "markdown", "id": "0acb2393", "metadata": {}, "source": [ "### Step 4: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "dc77b2d0", "metadata": {}, "outputs": [], "source": [ "# 1. Get the SOFT and matrix file paths again \n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "print(f\"Matrix file found: {matrix_file}\")\n", "\n", "# 2. Use the get_genetic_data function from the library to get the gene_data\n", "try:\n", " gene_data = get_genetic_data(matrix_file)\n", " print(f\"Gene data shape: {gene_data.shape}\")\n", " \n", " # 3. Print the first 20 row IDs (gene or probe identifiers)\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" ] }, { "cell_type": "markdown", "id": "0273c6ce", "metadata": {}, "source": [ "### Step 5: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": null, "id": "e9893739", "metadata": {}, "outputs": [], "source": [ "# Review the gene identifiers shown in the output\n", "# These appear to be numeric identifiers (1, 2, 24, 25...) rather than standard human gene symbols\n", "# Standard human gene symbols would typically be alphabetic like BRCA1, TP53, etc.\n", "# Therefore, these identifiers need to be mapped to gene symbols\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "cbcc3900", "metadata": {}, "source": [ "### Step 6: Gene Annotation" ] }, { "cell_type": "code", "execution_count": null, "id": "306ef120", "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. 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", "# Check for gene information in the SPOT_ID.1 column which appears to contain gene names\n", "print(\"\\nAnalyzing SPOT_ID.1 column for gene symbols:\")\n", "if 'SPOT_ID.1' in gene_annotation.columns:\n", " # Extract a few sample values\n", " sample_values = gene_annotation['SPOT_ID.1'].head(3).tolist()\n", " for i, value in enumerate(sample_values):\n", " print(f\"Sample {i+1} excerpt: {value[:200]}...\") # Print first 200 chars\n", " # Test the extract_human_gene_symbols function on these values\n", " symbols = extract_human_gene_symbols(value)\n", " print(f\" Extracted gene symbols: {symbols}\")\n", "\n", "# Try to find the probe IDs in the gene annotation\n", "gene_data_id_prefix = gene_data.index[0].split('_')[0] # Get prefix of first gene ID\n", "print(f\"\\nGene data ID prefix: {gene_data_id_prefix}\")\n", "\n", "# Look for columns that might match the gene data IDs\n", "for col in gene_annotation.columns:\n", " if gene_annotation[col].astype(str).str.contains(gene_data_id_prefix).any():\n", " print(f\"Column '{col}' contains values matching gene data ID pattern\")\n", "\n", "# Check if there's any column that might contain transcript or gene IDs\n", "print(\"\\nChecking for columns containing transcript or gene related terms:\")\n", "for col in gene_annotation.columns:\n", " if any(term in col.upper() for term in ['GENE', 'TRANSCRIPT', 'SYMBOL', 'NAME', 'DESCRIPTION']):\n", " print(f\"Column '{col}' may contain gene-related information\")\n", " # Show sample values\n", " print(f\"Sample values: {gene_annotation[col].head(3).tolist()}\")\n" ] }, { "cell_type": "markdown", "id": "72559510", "metadata": {}, "source": [ "### Step 7: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": null, "id": "9d097843", "metadata": {}, "outputs": [], "source": [ "# Analyze the structure of the gene data identifiers\n", "print(\"Gene data index structure:\")\n", "print(gene_data.index[:5].tolist())\n", "\n", "# First, we need to determine if the SPOT_ID column in gene_annotation might contain gene symbols\n", "# Check if there's a relationship between gene_data index and gene_annotation ID\n", "gene_id_set = set(gene_data.index.astype(str))\n", "annotation_id_set = set(gene_annotation['ID'].astype(str))\n", "\n", "# Check the overlap between gene_data IDs and gene_annotation IDs\n", "overlap = gene_id_set.intersection(annotation_id_set)\n", "print(f\"\\nOverlap between gene data IDs and gene annotation IDs: {len(overlap)} IDs\")\n", "print(f\"Example overlapping IDs: {list(overlap)[:5] if overlap else 'None'}\")\n", "\n", "# Since we don't have clear gene symbols in our annotation, we'll check if the SPOT_ID column might contain information\n", "# that can be parsed to extract gene symbols\n", "print(\"\\nAnalyzing SPOT_ID column for potential gene information:\")\n", "spot_id_examples = gene_annotation['SPOT_ID'].dropna().head(10).tolist()\n", "print(f\"SPOT_ID examples: {spot_id_examples}\")\n", "\n", "# Try to extract gene symbols from SPOT_ID values\n", "gene_symbols_extracted = [extract_human_gene_symbols(str(id_val)) for id_val in spot_id_examples]\n", "print(f\"Extracted gene symbols from SPOT_ID: {gene_symbols_extracted}\")\n", "\n", "# If we can't find clear gene symbols from the annotation, we need another approach\n", "# This is a special case where we might need to use the SPOT_ID as a temporary gene identifier\n", "# and advise that proper gene mapping would require additional annotation data\n", "\n", "# Since we have limited information in the annotation, we'll create a simple mapping using SPOT_ID\n", "# assuming it might contain some biological information even if not standard gene symbols\n", "prob_col = 'ID'\n", "gene_col = 'SPOT_ID' # Using SPOT_ID as our best available option\n", "\n", "# Create a mapping dataframe - the best we can do with available annotation\n", "mapping_df = gene_annotation[[prob_col, gene_col]].dropna()\n", "mapping_df = mapping_df.rename(columns={gene_col: 'Gene'})\n", "mapping_df = mapping_df.astype({'ID': 'str'})\n", "\n", "print(\"\\nMapping dataframe created:\")\n", "print(f\"Shape: {mapping_df.shape}\")\n", "print(mapping_df.head())\n", "\n", "# Check if mapping covers gene_data IDs\n", "coverage = len(set(mapping_df['ID']).intersection(gene_id_set)) / len(gene_id_set) * 100\n", "print(f\"Mapping covers {coverage:.2f}% of gene_data IDs\")\n", "\n", "# Apply the gene mapping to convert probe-level measurements to gene expression\n", "try:\n", " gene_data = apply_gene_mapping(gene_data, mapping_df)\n", " print(\"\\nGene expression data created:\")\n", " print(f\"Shape: {gene_data.shape}\")\n", " print(f\"First few gene symbols: {gene_data.index[:5].tolist()}\")\n", "except Exception as e:\n", " print(f\"Error during gene mapping: {e}\")\n", " \n", " # Alternative approach if the mapping fails - create a simple one-to-one mapping\n", " # This is not ideal but allows the pipeline to continue\n", " print(\"\\nFalling back to simplified mapping approach...\")\n", " \n", " # Create a mapping where each probe ID maps to itself (preserving the data)\n", " # This is a workaround when proper gene symbols aren't available\n", " fallback_mapping = pd.DataFrame({'ID': gene_data.index, 'Gene': gene_data.index})\n", " gene_data = apply_gene_mapping(gene_data, fallback_mapping)\n", " print(f\"Fallback gene expression data shape: {gene_data.shape}\")\n", " print(f\"First few identifiers: {gene_data.index[:5].tolist()}\")\n", " \n", " # Add a note about the limitations of this mapping\n", " print(\"NOTE: Unable to map to standard gene symbols. Using probe IDs as gene identifiers.\")\n", "\n", "# Print a summary of the gene data\n", "print(\"\\nSummary of mapped gene expression data:\")\n", "print(f\"Number of genes: {gene_data.shape[0]}\")\n", "print(f\"Number of samples: {gene_data.shape[1]}\")\n" ] }, { "cell_type": "markdown", "id": "ebf53e1f", "metadata": {}, "source": [ "### Step 8: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": null, "id": "593dcfe0", "metadata": {}, "outputs": [], "source": [ "# 1. Normalize gene symbols in the gene expression data\n", "# Use normalize_gene_symbols_in_index to standardize gene symbols\n", "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"Gene data shape before normalization: {gene_data.shape}\")\n", "print(f\"Gene data shape after normalization: {normalized_gene_data.shape}\")\n", "\n", "# Save the normalized gene data to file\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 expression data saved to {out_gene_data_file}\")\n", "\n", "# Load the actual clinical data from the matrix file that was previously obtained in Step 1\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", "# Get preview of clinical data to understand its structure\n", "print(\"Original clinical data preview:\")\n", "print(clinical_data.head())\n", "\n", "# 2. If we have trait data available, proceed with linking\n", "if trait_row is not None:\n", " # Extract clinical features using the original clinical data\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", " print(f\"Selected clinical data shape: {selected_clinical_df.shape}\")\n", " print(\"Clinical data preview:\")\n", " print(selected_clinical_df.head())\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 processing: {linked_data.shape}\")\n", " print(\"Linked data preview (first 5 rows, 5 columns):\")\n", " print(linked_data.iloc[:5, :5] if not linked_data.empty else \"Empty dataframe\")\n", "\n", " # 3. Handle missing values\n", " try:\n", " linked_data = handle_missing_values(linked_data, trait)\n", " print(f\"Data shape after handling missing values: {linked_data.shape}\")\n", " except Exception as e:\n", " print(f\"Error handling missing values: {e}\")\n", " linked_data = pd.DataFrame() # Create empty dataframe if error occurs\n", "\n", " # 4. Check for bias in features\n", " if not linked_data.empty and linked_data.shape[0] > 0:\n", " is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n", " print(f\"Data shape after removing biased features: {linked_data.shape}\")\n", " else:\n", " is_biased = True\n", " print(\"Cannot check for bias as dataframe is empty or has no rows after missing value handling\")\n", "\n", " # 5. Validate and save cohort information\n", " note = \"\"\n", " if linked_data.empty or linked_data.shape[0] == 0:\n", " note = \"Dataset contains gene expression data related to liver fibrosis progression, but linking clinical and genetic data failed, possibly due to mismatched sample IDs.\"\n", " else:\n", " note = \"Dataset contains gene expression data for liver fibrosis progression, which is relevant to liver cirrhosis research.\"\n", " \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_biased,\n", " df=linked_data,\n", " note=note\n", " )\n", "\n", " # 6. Save the linked data if 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(\"Dataset is not usable for analysis. No linked data file saved.\")\n", "else:\n", " # If no trait data available, validate with trait_available=False\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=False,\n", " is_biased=True, # Set to True since we can't use data without trait\n", " df=pd.DataFrame(), # Empty DataFrame\n", " note=\"Dataset contains gene expression data but lacks proper clinical trait information for liver cirrhosis analysis.\"\n", " )\n", " \n", " print(\"Dataset is not usable for liver cirrhosis analysis due to lack of clinical trait data. No linked data file saved.\")" ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 5 }