{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "c23e26e9", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:27:07.303078Z", "iopub.status.busy": "2025-03-25T07:27:07.302965Z", "iopub.status.idle": "2025-03-25T07:27:07.469603Z", "shell.execute_reply": "2025-03-25T07:27:07.469239Z" } }, "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 = \"Large_B-cell_Lymphoma\"\n", "cohort = \"GSE182362\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Large_B-cell_Lymphoma\"\n", "in_cohort_dir = \"../../input/GEO/Large_B-cell_Lymphoma/GSE182362\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Large_B-cell_Lymphoma/GSE182362.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Large_B-cell_Lymphoma/gene_data/GSE182362.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Large_B-cell_Lymphoma/clinical_data/GSE182362.csv\"\n", "json_path = \"../../output/preprocess/Large_B-cell_Lymphoma/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "2013e87c", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "e8e76893", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:27:07.471087Z", "iopub.status.busy": "2025-03-25T07:27:07.470935Z", "iopub.status.idle": "2025-03-25T07:27:07.524309Z", "shell.execute_reply": "2025-03-25T07:27:07.523968Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"miR-155-regulated mTOR and Toll-like receptor 5 in gastric diffuse large B-cell lymphoma\"\n", "!Series_summary\t\"This SuperSeries is composed of the SubSeries listed below.\"\n", "!Series_overall_design\t\"Refer to individual Series\"\n", "Sample Characteristics Dictionary:\n", "{0: ['cell line: B-cell lymphoma cell line U2932', 'tissue: cell line derived from diffuse large B-cell lymphoma'], 1: ['tissue: cell line derived from diffuse large B-cell lymphoma', 'treatment: transfected with miR-200c'], 2: ['treatment: transfected with an empty vector', 'treatment: transfected with miR-200a', 'treatment: transfected with miR-200b', nan]}\n" ] } ], "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": "5dca1be3", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "cb3ada9a", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:27:07.525582Z", "iopub.status.busy": "2025-03-25T07:27:07.525473Z", "iopub.status.idle": "2025-03-25T07:27:07.530122Z", "shell.execute_reply": "2025-03-25T07:27:07.529818Z" } }, "outputs": [], "source": [ "import os\n", "import pandas as pd\n", "import json\n", "from typing import Dict, Any, Callable, Optional\n", "\n", "# 1. Gene Expression Data Availability\n", "# The \"SuperSeries\" description suggests this might include gene expression data\n", "# alongside miRNA data, as it's common for SuperSeries to contain multiple data types\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# Looking at the sample characteristics, we can determine:\n", "\n", "# 2.1 Data Availability\n", "# From the sample characteristics, all samples appear to be DLBCL cell lines,\n", "# making the trait constant across all samples. As per instructions,\n", "# constant features are considered not available.\n", "trait_row = None # Since all samples appear to be DLBCL\n", "\n", "# Age and gender are not available in the sample characteristics\n", "age_row = None\n", "gender_row = None\n", "\n", "# 2.2 Data Type Conversion Functions\n", "def convert_trait(value):\n", " \"\"\"Convert trait data (DLBCL) to binary format.\"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract the value part after colon if it exists\n", " if isinstance(value, str) and ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Check if the value indicates DLBCL\n", " if 'diffuse large B-cell lymphoma' in value.lower():\n", " return 1\n", " else:\n", " return 0\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age data to numerical format.\"\"\"\n", " # Not used in this dataset, but included for completeness\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender data to binary format (0=female, 1=male).\"\"\"\n", " # Not used in this dataset, but included for completeness\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Determine trait data availability based on trait_row\n", "is_trait_available = trait_row is not None\n", "\n", "# Save cohort information\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", "# We skip this step since trait_row is None (constant trait)\n", "if trait_row is not None:\n", " # This block will be skipped based on our analysis\n", " # but keeping the structure in case trait_row changes in future\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " \n", " selected_clinical_df = geo_select_clinical_features(\n", " clinical_df=clinical_data, # Use the clinical_data from previous steps\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 selected clinical features\n", " preview = preview_df(selected_clinical_df)\n", " print(\"Preview of clinical data:\", preview)\n", " \n", " # Save the clinical data\n", " selected_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": "a4240bae", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "ce32a7ff", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:27:07.531143Z", "iopub.status.busy": "2025-03-25T07:27:07.531037Z", "iopub.status.idle": "2025-03-25T07:27:07.565919Z", "shell.execute_reply": "2025-03-25T07:27:07.565609Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Examining matrix file structure...\n", "Line 0: !Series_title\t\"miR-155-regulated mTOR and Toll-like receptor 5 in gastric diffuse large B-cell lymphoma\"\n", "Line 1: !Series_geo_accession\t\"GSE182362\"\n", "Line 2: !Series_status\t\"Public on Feb 09 2022\"\n", "Line 3: !Series_submission_date\t\"Aug 18 2021\"\n", "Line 4: !Series_last_update_date\t\"Feb 09 2022\"\n", "Line 5: !Series_pubmed_id\t\"34913612\"\n", "Line 6: !Series_summary\t\"This SuperSeries is composed of the SubSeries listed below.\"\n", "Line 7: !Series_overall_design\t\"Refer to individual Series\"\n", "Line 8: !Series_type\t\"Expression profiling by array\"\n", "Line 9: !Series_type\t\"Non-coding RNA profiling by array\"\n", "Found table marker at line 70\n", "First few lines after marker:\n", "\"ID_REF\"\t\"GSM5527571\"\t\"GSM5527572\"\t\"GSM5527573\"\t\"GSM5527574\"\n", "\"A_19_P00315452\"\t34.088\t30.238\t57.407\t19.554\n", "\"A_19_P00315459\"\t903.948\t986.916\t922.612\t764.945\n", "\"A_19_P00315469\"\t7.125\t9.957\t8.062\t8.2\n", "\"A_19_P00315473\"\t6.314\t24.339\t8.542\t7.055\n", "Total lines examined: 71\n", "\n", "Attempting to extract gene data from matrix file...\n", "Successfully extracted gene data with 42405 rows\n", "First 20 gene IDs:\n", "Index(['A_19_P00315452', 'A_19_P00315459', 'A_19_P00315469', 'A_19_P00315473',\n", " 'A_19_P00315482', 'A_19_P00315490', 'A_19_P00315492', 'A_19_P00315493',\n", " 'A_19_P00315496', 'A_19_P00315499', 'A_19_P00315502', 'A_19_P00315504',\n", " 'A_19_P00315506', 'A_19_P00315508', 'A_19_P00315518', 'A_19_P00315519',\n", " 'A_19_P00315523', 'A_19_P00315524', 'A_19_P00315526', 'A_19_P00315527'],\n", " dtype='object', name='ID')\n", "\n", "Gene expression data available: True\n" ] } ], "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": "5b39fda2", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "3152c04d", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:27:07.566972Z", "iopub.status.busy": "2025-03-25T07:27:07.566866Z", "iopub.status.idle": "2025-03-25T07:27:07.568674Z", "shell.execute_reply": "2025-03-25T07:27:07.568384Z" } }, "outputs": [], "source": [ "# The gene identifiers in the gene expression data are in the format 'A_19_P00315452',\n", "# which are Agilent microarray probe IDs rather than standard human gene symbols.\n", "# These IDs need to be mapped to standard gene symbols for proper analysis.\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "2d030b0f", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "d2dde713", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:27:07.569655Z", "iopub.status.busy": "2025-03-25T07:27:07.569554Z", "iopub.status.idle": "2025-03-25T07:27:10.613663Z", "shell.execute_reply": "2025-03-25T07:27:10.613292Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Extracting gene annotation data from SOFT file...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Successfully extracted gene annotation data with 1259045 rows\n", "\n", "Gene annotation preview (first few rows):\n", "{'ID': ['(+)E1A_r60_1', '(+)E1A_r60_3', '(+)E1A_r60_a104', '(+)E1A_r60_a107', '(+)E1A_r60_a135'], 'SPOT_ID': ['(+)E1A_r60_1', '(+)E1A_r60_3', '(+)E1A_r60_a104', '(+)E1A_r60_a107', '(+)E1A_r60_a135'], 'CONTROL_TYPE': ['pos', 'pos', 'pos', 'pos', 'pos'], 'REFSEQ': [nan, nan, nan, nan, nan], 'GB_ACC': [nan, nan, nan, nan, nan], 'GENE': [nan, nan, nan, nan, nan], 'GENE_SYMBOL': [nan, nan, nan, nan, nan], 'GENE_NAME': [nan, nan, nan, nan, nan], 'UNIGENE_ID': [nan, nan, nan, nan, nan], 'ENSEMBL_ID': [nan, nan, nan, nan, nan], 'TIGR_ID': [nan, nan, nan, nan, nan], 'ACCESSION_STRING': [nan, nan, nan, nan, nan], 'CHROMOSOMAL_LOCATION': [nan, nan, nan, nan, nan], 'CYTOBAND': [nan, nan, nan, nan, nan], 'DESCRIPTION': [nan, nan, nan, nan, nan], 'GO_ID': [nan, nan, nan, nan, nan], 'SEQUENCE': [nan, nan, nan, nan, nan]}\n", "\n", "Column names in gene annotation data:\n", "['ID', 'SPOT_ID', 'CONTROL_TYPE', 'REFSEQ', 'GB_ACC', 'GENE', 'GENE_SYMBOL', 'GENE_NAME', 'UNIGENE_ID', 'ENSEMBL_ID', 'TIGR_ID', 'ACCESSION_STRING', 'CHROMOSOMAL_LOCATION', 'CYTOBAND', 'DESCRIPTION', 'GO_ID', 'SEQUENCE']\n", "\n", "The dataset contains GenBank accessions (GB_ACC) that could be used for gene mapping.\n", "Number of rows with GenBank accessions: 105997 out of 1259045\n", "\n", "The dataset contains genomic regions (SPOT_ID) that could be used for location-based gene mapping.\n", "Example SPOT_ID format: (+)E1A_r60_1\n" ] } ], "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": "2c565eba", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "d434a305", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:27:10.615059Z", "iopub.status.busy": "2025-03-25T07:27:10.614922Z", "iopub.status.idle": "2025-03-25T07:27:10.945801Z", "shell.execute_reply": "2025-03-25T07:27:10.945406Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Preparing gene identifier mapping...\n", "Created mapping dataframe with 124298 rows\n", "Mapping contains 56169 unique probes and 67260 unique genes\n", "Converting probe measurements to gene expression data...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Successfully mapped probe IDs to gene symbols. Final gene expression data has 21773 genes.\n", "First 10 gene symbols:\n", "Index(['A-', 'A-52', 'A-E', 'A-I', 'A-II', 'A-IV', 'A-V', 'A0', 'A1', 'A1-'], dtype='object', name='Gene')\n", "Gene expression data saved to ../../output/preprocess/Large_B-cell_Lymphoma/gene_data/GSE182362.csv\n" ] } ], "source": [ "# 1. Determine the mapping columns\n", "# The gene expression data has IDs in the format 'A_19_P00315452'\n", "# In the gene annotation data, these IDs correspond to the 'ID' column\n", "# The 'GENE_SYMBOL' column contains the gene symbols we want to map to\n", "\n", "print(\"Preparing gene identifier mapping...\")\n", "\n", "# 2. Extract the mapping between probe IDs and gene symbols\n", "# Get gene mapping dataframe by extracting the two relevant columns\n", "try:\n", " # Extract ID and GENE_SYMBOL columns for mapping\n", " mapping_df = get_gene_mapping(gene_annotation, \"ID\", \"GENE_SYMBOL\")\n", " print(f\"Created mapping dataframe with {len(mapping_df)} rows\")\n", " \n", " # Check how many unique probes and genes are in the mapping\n", " unique_probes = mapping_df['ID'].nunique()\n", " unique_genes = mapping_df['Gene'].nunique()\n", " print(f\"Mapping contains {unique_probes} unique probes and {unique_genes} unique genes\")\n", " \n", " # 3. Convert probe-level measurements to gene expression data\n", " print(\"Converting probe measurements to gene expression data...\")\n", " gene_data = apply_gene_mapping(gene_data, mapping_df)\n", " \n", " # Check the result\n", " if gene_data.empty:\n", " print(\"Warning: Gene expression dataframe is empty after mapping\")\n", " is_gene_available = False\n", " else:\n", " print(f\"Successfully mapped probe IDs to gene symbols. Final gene expression data has {len(gene_data)} genes.\")\n", " print(\"First 10 gene symbols:\")\n", " print(gene_data.index[:10])\n", " \n", " # Save the gene data to file\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", " \n", "except Exception as e:\n", " print(f\"Error in gene mapping process: {str(e)}\")\n", " is_gene_available = False\n" ] }, { "cell_type": "markdown", "id": "0a52414e", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "5bac8f59", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:27:10.947267Z", "iopub.status.busy": "2025-03-25T07:27:10.947148Z", "iopub.status.idle": "2025-03-25T07:27:11.091283Z", "shell.execute_reply": "2025-03-25T07:27:11.090877Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Normalizing gene symbols...\n", "Loading gene data from previous step...\n", "Gene data shape before normalization: (21773, 4)\n", "Sample of gene symbols before normalization: ['A-', 'A-52', 'A-E', 'A-I', 'A-II', 'A-IV', 'A-V', 'A0', 'A1', 'A1-']\n", "After normalization: 19577 genes\n", "Gene data saved to ../../output/preprocess/Large_B-cell_Lymphoma/gene_data/GSE182362.csv\n", "\n", "Checking clinical data availability...\n", "No clinical data available for this cohort. Cannot proceed with linking.\n", "\n", "Performing final validation...\n", "Abnormality detected in the cohort: GSE182362. Preprocessing failed.\n", "\n", "Dataset usability for Large_B-cell_Lymphoma association studies: False\n", "Reason: Dataset does not contain clinical trait information for Large_B-cell_Lymphoma (all samples appear to be cell lines).\n" ] } ], "source": [ "# 1. Normalize gene symbols in the obtained gene expression data\n", "print(\"\\nNormalizing gene symbols...\")\n", "# Get the gene data from previous step if needed\n", "try:\n", " # First, check if we need to reload the gene data\n", " gene_data_path = \"../../output/preprocess/Large_B-cell_Lymphoma/gene_data/GSE182362.csv\"\n", " if os.path.exists(gene_data_path):\n", " print(\"Loading gene data from previous step...\")\n", " gene_data = pd.read_csv(gene_data_path, index_col=0)\n", " else:\n", " print(\"Gene data not found, recreating from previous steps...\")\n", " soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", " gene_annotation = get_gene_annotation(soft_file)\n", " gene_data = get_genetic_data(matrix_file)\n", " mapping_df = get_gene_mapping(gene_annotation, \"ID\", \"GENE_SYMBOL\")\n", " gene_data = apply_gene_mapping(gene_data, mapping_df)\n", " \n", " print(f\"Gene data shape before normalization: {gene_data.shape}\")\n", " print(\"Sample of gene symbols before normalization:\", gene_data.index[:10].tolist())\n", " \n", " # Use the normalize_gene_symbols_in_index function to standardize gene symbols\n", " normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", " print(f\"After normalization: {len(normalized_gene_data.index)} genes\")\n", " \n", " # Handle case where normalization results in 0 genes\n", " if len(normalized_gene_data.index) == 0:\n", " print(\"WARNING: Normalization resulted in 0 genes. Using original gene data for diagnostics.\")\n", " normalized_gene_data = gene_data # Use original data for diagnostic purposes\n", " is_gene_available = False # Mark that normalization failed\n", " else:\n", " is_gene_available = True\n", " \n", " # Save the normalized gene expression data\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\"Gene data saved to {out_gene_data_file}\")\n", " \n", "except Exception as e:\n", " print(f\"Error in gene normalization: {str(e)}\")\n", " is_gene_available = False\n", "\n", "# 2. Try to retrieve clinical data\n", "print(\"\\nChecking clinical data availability...\")\n", "try:\n", " # Recall from previous steps that trait_row was None, indicating no clinical data is available\n", " trait_row = None\n", " is_trait_available = trait_row is not None\n", " \n", " if is_trait_available:\n", " # This block should never execute as trait_row is None\n", " print(\"Clinical data is available.\")\n", " if os.path.exists(out_clinical_data_file):\n", " clinical_df = pd.read_csv(out_clinical_data_file)\n", " print(f\"Loaded clinical data with shape: {clinical_df.shape}\")\n", " else:\n", " print(\"Clinical data file not found.\")\n", " is_trait_available = False\n", " else:\n", " print(\"No clinical data available for this cohort. Cannot proceed with linking.\")\n", "except Exception as e:\n", " print(f\"Error checking clinical data: {str(e)}\")\n", " is_trait_available = False\n", "\n", "# 3. Since clinical data is not available, we can't create linked data\n", "linked_data = pd.DataFrame() # Empty DataFrame as placeholder\n", "is_biased = True # Consider it biased since we can't evaluate properly\n", "\n", "# 4. Validate and save cohort information\n", "print(\"\\nPerforming final validation...\")\n", "note = \"Dataset does not contain clinical trait information for Large_B-cell_Lymphoma (all samples appear to be cell lines).\"\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=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", "# 5. Report final status\n", "print(f\"\\nDataset usability for {trait} association studies: {is_usable}\")\n", "print(f\"Reason: {note}\")" ] } ], "metadata": { "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.16" } }, "nbformat": 4, "nbformat_minor": 5 }