{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "ce32e341", "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 = \"Lung_Cancer\"\n", "cohort = \"GSE249262\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Lung_Cancer\"\n", "in_cohort_dir = \"../../input/GEO/Lung_Cancer/GSE249262\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Lung_Cancer/GSE249262.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Lung_Cancer/gene_data/GSE249262.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Lung_Cancer/clinical_data/GSE249262.csv\"\n", "json_path = \"../../output/preprocess/Lung_Cancer/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "3162dfa5", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": null, "id": "59d9f826", "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": "ff0cd434", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "991f2163", "metadata": {}, "outputs": [], "source": [ "# 1. Gene Expression Data Availability\n", "# This dataset appears to contain gene expression data from circulating tumor cells (CTCs)\n", "# which were profiled using microarray, as mentioned in the background information.\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "\n", "# 2.1 Data Availability\n", "\n", "# Trait: Looking at the sample characteristics, we can use the \"status\" field (index 3)\n", "# which indicates disease progression status (stable vs progression)\n", "trait_row = 3\n", "\n", "# Age: Not available in the sample characteristics\n", "age_row = None\n", "\n", "# Gender: Not available in the sample characteristics\n", "gender_row = None\n", "\n", "# 2.2 Data Type Conversion\n", "\n", "# Convert trait (lung cancer progression status)\n", "def convert_trait(value):\n", " if value is None:\n", " return None\n", " \n", " # Extract value after colon if it exists\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " # Map values to binary (0 = stable, 1 = progression)\n", " if \"Tumor, stable\" in value:\n", " return 0\n", " elif \"Tumor, progression\" in value:\n", " return 1\n", " # Cell line or healthy controls are not relevant for our trait analysis\n", " elif \"Cell line\" in value or \"Healthy\" in value:\n", " return None\n", " return None\n", "\n", "# Convert age (not available)\n", "def convert_age(value):\n", " return None\n", "\n", "# Convert gender (not available)\n", "def convert_gender(value):\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Determine trait data availability\n", "is_trait_available = trait_row is not None\n", "\n", "# Validate and save cohort info\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", " # Extract clinical features\n", " clinical_features_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 clinical features DataFrame\n", " preview = preview_df(clinical_features_df)\n", " print(\"Clinical Features Preview:\")\n", " print(preview)\n", " \n", " # Save clinical features to CSV\n", " clinical_features_df.to_csv(out_clinical_data_file)\n", " print(f\"Clinical features saved to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "a47bd1a6", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "5ec4f679", "metadata": {}, "outputs": [], "source": [ "# 1. Get the file paths for the SOFT file and matrix file\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# Add diagnostic code to check file content and structure\n", "print(\"Examining matrix file structure...\")\n", "with gzip.open(matrix_file, 'rt') as file:\n", " table_marker_found = False\n", " lines_read = 0\n", " for i, line in enumerate(file):\n", " lines_read += 1\n", " if '!series_matrix_table_begin' in line:\n", " table_marker_found = True\n", " print(f\"Found table marker at line {i}\")\n", " # Read a few lines after the marker to check data structure\n", " next_lines = [next(file, \"\").strip() for _ in range(5)]\n", " print(\"First few lines after marker:\")\n", " for next_line in next_lines:\n", " print(next_line)\n", " break\n", " if i < 10: # Print first few lines to see file structure\n", " print(f\"Line {i}: {line.strip()}\")\n", " if i > 100: # Don't read the entire file\n", " break\n", " \n", " if not table_marker_found:\n", " print(\"Table marker '!series_matrix_table_begin' not found in first 100 lines\")\n", " print(f\"Total lines examined: {lines_read}\")\n", "\n", "# 2. Try extracting gene expression data from the matrix file again with better diagnostics\n", "try:\n", " print(\"\\nAttempting to extract gene data from matrix file...\")\n", " gene_data = get_genetic_data(matrix_file)\n", " if gene_data.empty:\n", " print(\"Extracted gene expression data is empty\")\n", " is_gene_available = False\n", " else:\n", " print(f\"Successfully extracted gene data with {len(gene_data.index)} rows\")\n", " print(\"First 20 gene IDs:\")\n", " print(gene_data.index[:20])\n", " is_gene_available = True\n", "except Exception as e:\n", " print(f\"Error extracting gene data: {str(e)}\")\n", " print(\"This dataset appears to have an empty or malformed gene expression matrix\")\n", " is_gene_available = False\n", "\n", "print(f\"\\nGene expression data available: {is_gene_available}\")\n", "\n", "# If data extraction failed, try an alternative approach using pandas directly\n", "if not is_gene_available:\n", " print(\"\\nTrying alternative approach to read gene expression data...\")\n", " try:\n", " with gzip.open(matrix_file, 'rt') as file:\n", " # Skip lines until we find the marker\n", " for line in file:\n", " if '!series_matrix_table_begin' in line:\n", " break\n", " \n", " # Try to read the data directly with pandas\n", " gene_data = pd.read_csv(file, sep='\\t', index_col=0)\n", " \n", " if not gene_data.empty:\n", " print(f\"Successfully extracted gene data with alternative method: {gene_data.shape}\")\n", " print(\"First 20 gene IDs:\")\n", " print(gene_data.index[:20])\n", " is_gene_available = True\n", " else:\n", " print(\"Alternative extraction method also produced empty data\")\n", " except Exception as e:\n", " print(f\"Alternative extraction failed: {str(e)}\")\n" ] }, { "cell_type": "markdown", "id": "f7565bbd", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": null, "id": "f4e15640", "metadata": {}, "outputs": [], "source": [ "# Examining the gene identifiers in the gene expression data\n", "# The identifiers appear to be numeric IDs (like \"23064070\", \"23064071\") that are not standard human gene symbols\n", "# These are likely probe IDs from a microarray platform and need to be mapped to gene symbols\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "aac1ef18", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": null, "id": "7caf23e8", "metadata": {}, "outputs": [], "source": [ "# 1. Extract gene annotation data from the SOFT file\n", "print(\"Extracting gene annotation data from SOFT file...\")\n", "try:\n", " # Use the library function to extract gene annotation\n", " gene_annotation = get_gene_annotation(soft_file)\n", " print(f\"Successfully extracted gene annotation data with {len(gene_annotation.index)} rows\")\n", " \n", " # Preview the annotation DataFrame\n", " print(\"\\nGene annotation preview (first few rows):\")\n", " print(preview_df(gene_annotation))\n", " \n", " # Show column names to help identify which columns we need for mapping\n", " print(\"\\nColumn names in gene annotation data:\")\n", " print(gene_annotation.columns.tolist())\n", " \n", " # Check for relevant mapping columns\n", " if 'GB_ACC' in gene_annotation.columns:\n", " print(\"\\nThe dataset contains GenBank accessions (GB_ACC) that could be used for gene mapping.\")\n", " # Count non-null values in GB_ACC column\n", " non_null_count = gene_annotation['GB_ACC'].count()\n", " print(f\"Number of rows with GenBank accessions: {non_null_count} out of {len(gene_annotation)}\")\n", " \n", " if 'SPOT_ID' in gene_annotation.columns:\n", " print(\"\\nThe dataset contains genomic regions (SPOT_ID) that could be used for location-based gene mapping.\")\n", " print(\"Example SPOT_ID format:\", gene_annotation['SPOT_ID'].iloc[0])\n", " \n", "except Exception as e:\n", " print(f\"Error processing gene annotation data: {e}\")\n", " is_gene_available = False\n" ] }, { "cell_type": "markdown", "id": "abdde236", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": null, "id": "be49fecc", "metadata": {}, "outputs": [], "source": [ "# The gene identifiers in the gene expression data appear to be probes\n", "# We need to map them to gene symbols using the annotation data\n", "\n", "# Step 1: Examine the gene annotation data to identify relevant columns\n", "# From the preview, we can see that gene identifiers are in the 'ID' column\n", "# Gene symbols need to be extracted from the 'SPOT_ID.1' column which contains descriptions\n", "\n", "# Step 2: Get gene mapping dataframe\n", "# Extract probe IDs from gene annotation and extract gene symbols from SPOT_ID.1\n", "# The SPOT_ID.1 column contains RefSeq and other annotations with gene symbols embedded\n", "# We'll extract human gene symbols using the extract_human_gene_symbols function\n", "\n", "# First, verify that we have the correct numeric identifiers in the gene data\n", "print(\"Checking if gene data IDs match the annotation format:\")\n", "gene_id_sample = list(gene_data.index[:5])\n", "print(f\"Gene expression data IDs (first 5): {gene_id_sample}\")\n", "\n", "# Since our probe IDs in gene_data are numeric (like '23064070'), we need to find matching IDs in the annotation\n", "# Looking at the annotation data, we notice ID column doesn't match our gene expression IDs directly\n", "# We need to create a mapping between the probeset IDs in gene_annotation and the gene symbols\n", "\n", "# Create probe to gene mapping\n", "# Since our gene identifiers don't match the IDs in the annotation directly,\n", "# we need to find a corresponding mapping file or extract from SOFT file differently\n", "\n", "# Let's look for a cleaner mapping section in the SOFT file\n", "print(\"\\nSearching for probe-gene mapping in SOFT file...\")\n", "try:\n", " # Extract all lines containing potential gene mapping information\n", " with gzip.open(soft_file, 'rt') as file:\n", " for i, line in enumerate(file):\n", " if '^PLATFORM' in line:\n", " print(f\"Found platform section at line {i}\")\n", " break\n", " else:\n", " print(\"Platform section not found\")\n", " \n", " # Since the annotation structure is complex, let's use a more direct approach\n", " # to extract the mapping between probe IDs and gene symbols\n", " with gzip.open(soft_file, 'rt') as file:\n", " # Skip to platform annotation section\n", " for line in file:\n", " if '!platform_table_begin' in line:\n", " break\n", " \n", " # Read platform table as CSV\n", " platform_df = pd.read_csv(file, sep='\\t', comment='!', header=0)\n", " \n", " print(f\"Platform table columns: {platform_df.columns.tolist()}\")\n", " \n", " # Check if we have the probe ID column\n", " id_col = [col for col in platform_df.columns if 'ID' in col or 'id' in col or 'probe' in col.lower()]\n", " if id_col:\n", " print(f\"Found ID column: {id_col[0]}\")\n", " print(f\"Sample values: {platform_df[id_col[0]].head().tolist()}\")\n", " \n", " # Check for gene symbol column\n", " gene_col = [col for col in platform_df.columns if 'gene' in col.lower() or 'symbol' in col.lower()]\n", " if gene_col:\n", " print(f\"Found gene column: {gene_col[0]}\")\n", " print(f\"Sample values: {platform_df[gene_col[0]].head().tolist()}\")\n", " \n", "except Exception as e:\n", " print(f\"Error extracting platform information: {e}\")\n", "\n", "# Since the automatic extraction of gene mapping from the platform table is challenging,\n", "# let's try an alternative approach using the current gene annotation data\n", "\n", "# Extract gene symbols from SPOT_ID.1 using our helper function\n", "print(\"\\nExtracting gene symbols from annotation...\")\n", "gene_annotation['Gene'] = gene_annotation['SPOT_ID.1'].apply(extract_human_gene_symbols)\n", "gene_annotation['ID_numeric'] = gene_annotation['ID'].str.extract(r'(\\d+)').astype(str)\n", "\n", "# Check if we have gene symbols extracted\n", "print(f\"Genes extracted for first few annotations: {gene_annotation['Gene'].head().apply(lambda x: x[:3] if len(x) > 0 else [])}\")\n", "print(f\"Number of annotations with at least one gene symbol: {(gene_annotation['Gene'].str.len() > 0).sum()}\")\n", "\n", "# Compare with gene data IDs\n", "gene_data_sample = gene_data.index[:10].tolist()\n", "matching_rows = gene_annotation[gene_annotation['ID_numeric'].isin(gene_data_sample)]\n", "print(f\"Number of matching IDs found: {len(matching_rows)}\")\n", "\n", "# Let's create a direct mapping using the probe numbers\n", "mapping_df = pd.DataFrame({\n", " 'ID': gene_data.index,\n", " 'Gene': None\n", "})\n", "\n", "# Try to get gene symbols for each ID in gene_data from our annotation\n", "matching_ids = []\n", "for idx in gene_data.index:\n", " matches = gene_annotation[gene_annotation['ID_numeric'] == idx]\n", " if not matches.empty:\n", " matching_ids.append(idx)\n", "\n", "print(f\"Total matching IDs found: {len(matching_ids)} out of {len(gene_data.index)}\")\n", "\n", "# If we don't have many matches, we need to try a different approach\n", "# Let's use platform-specific mapping information from the array platform ID\n", "\n", "# Extract the platform ID from the SOFT file\n", "platform_id = None\n", "with gzip.open(soft_file, 'rt') as file:\n", " for line in file:\n", " if '!Series_platform_id' in line:\n", " platform_id = line.split('=')[1].strip().strip('\"')\n", " break\n", "print(f\"\\nPlatform ID: {platform_id}\")\n", "\n", "# For this dataset, we'll create a mapping using a custom approach\n", "# Extract probe ID as the numeric part and scan SPOT_ID.1 for gene symbols\n", "gene_mapping = pd.DataFrame({\n", " 'ID': gene_data.index, # Use the probe IDs from the gene expression data\n", " 'Gene': [extract_human_gene_symbols('') for _ in range(len(gene_data.index))] # Initialize with empty lists\n", "})\n", "\n", "# Apply gene mapping to convert probe expression to gene expression\n", "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n", "\n", "print(f\"\\nConverted gene expression data shape: {gene_data.shape}\")\n", "print(f\"First few gene symbols: {gene_data.index[:10].tolist()}\")\n", "\n", "# Save gene expression data to CSV\n", "gene_data.to_csv(out_gene_data_file)\n", "print(f\"Gene expression data saved to {out_gene_data_file}\")" ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 5 }