{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "9bfc6152", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:43:04.042548Z", "iopub.status.busy": "2025-03-25T05:43:04.042369Z", "iopub.status.idle": "2025-03-25T05:43:04.212355Z", "shell.execute_reply": "2025-03-25T05:43:04.212024Z" } }, "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 = \"Hepatitis\"\n", "cohort = \"GSE66843\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Hepatitis\"\n", "in_cohort_dir = \"../../input/GEO/Hepatitis/GSE66843\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Hepatitis/GSE66843.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Hepatitis/gene_data/GSE66843.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Hepatitis/clinical_data/GSE66843.csv\"\n", "json_path = \"../../output/preprocess/Hepatitis/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "fc7c6d38", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "14af30fd", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:43:04.213839Z", "iopub.status.busy": "2025-03-25T05:43:04.213691Z", "iopub.status.idle": "2025-03-25T05:43:04.312536Z", "shell.execute_reply": "2025-03-25T05:43:04.312223Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"A cell-based model unravels drivers for hepatocarcinogenesis and targets for clinical chemoprevention\"\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: ['time post infection: Day 3 post infection', 'time post infection: Day 7 post infection', 'time post infection: Day 10 post infection'], 1: ['infection: Mock infection (control)', 'infection: HCV Jc1 infection'], 2: ['cell line: Huh7.5.1']}\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": "6d216771", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "cc79ae11", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:43:04.313748Z", "iopub.status.busy": "2025-03-25T05:43:04.313638Z", "iopub.status.idle": "2025-03-25T05:43:04.318411Z", "shell.execute_reply": "2025-03-25T05:43:04.318104Z" } }, "outputs": [], "source": [ "import pandas as pd\n", "import os\n", "import json\n", "from typing import Optional, Dict, Any, Callable\n", "\n", "# Determine Gene Expression Availability\n", "# This dataset appears to be HCV infection in cell lines (Huh7.5.1), which likely contains gene expression data\n", "is_gene_available = True\n", "\n", "# Analyze trait, age, and gender availability\n", "# From the sample characteristics, we have:\n", "# - trait appears to be infection status (HCV vs Mock)\n", "# - no age data (these are cell lines)\n", "# - no gender data (these are cell lines)\n", "\n", "trait_row = 1 # The row containing infection status\n", "age_row = None # No age data for cell lines\n", "gender_row = None # No gender data for cell lines\n", "\n", "# Define conversion functions\n", "def convert_trait(value):\n", " \"\"\"Convert infection status to binary: HCV=1, Mock=0\"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract value after colon if present\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Convert to binary\n", " if 'mock' in value.lower() or 'control' in value.lower():\n", " return 0\n", " elif 'hcv' in value.lower() or 'jc1' in value.lower():\n", " return 1\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Placeholder function for age conversion\"\"\"\n", " # Not applicable for this dataset\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Placeholder function for gender conversion\"\"\"\n", " # Not applicable for this dataset\n", " return None\n", "\n", "# Determine trait data availability\n", "is_trait_available = trait_row is not None\n", "\n", "# Save metadata with 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 trait_row is not None:\n", " # Load clinical data from a previous step\n", " clinical_data_path = os.path.join(in_cohort_dir, \"clinical_data.csv\")\n", " if os.path.exists(clinical_data_path):\n", " clinical_data = pd.read_csv(clinical_data_path)\n", " \n", " # Extract clinical features\n", " clinical_features = 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 extracted features\n", " preview = preview_df(clinical_features)\n", " print(\"Preview of clinical features:\")\n", " print(preview)\n", " \n", " # Create directory if it doesn't exist\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " \n", " # Save the clinical features\n", " clinical_features.to_csv(out_clinical_data_file, index=False)\n", " print(f\"Clinical features saved to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "54faabde", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "ab6aef94", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:43:04.319477Z", "iopub.status.busy": "2025-03-25T05:43:04.319371Z", "iopub.status.idle": "2025-03-25T05:43:04.421134Z", "shell.execute_reply": "2025-03-25T05:43:04.420739Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Extracting gene data from matrix file:\n", "Successfully extracted gene data with 46116 rows\n", "First 20 gene IDs:\n", "Index(['ILMN_1343291', 'ILMN_1343295', 'ILMN_1651199', 'ILMN_1651209',\n", " 'ILMN_1651210', 'ILMN_1651221', 'ILMN_1651228', 'ILMN_1651229',\n", " 'ILMN_1651230', 'ILMN_1651232', 'ILMN_1651235', 'ILMN_1651236',\n", " 'ILMN_1651237', 'ILMN_1651238', 'ILMN_1651249', 'ILMN_1651253',\n", " 'ILMN_1651254', 'ILMN_1651259', 'ILMN_1651260', 'ILMN_1651262'],\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", "# 2. Extract gene expression data from the matrix file\n", "try:\n", " print(\"Extracting 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: {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" ] }, { "cell_type": "markdown", "id": "25e6321b", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "d876449c", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:43:04.422451Z", "iopub.status.busy": "2025-03-25T05:43:04.422337Z", "iopub.status.idle": "2025-03-25T05:43:04.424245Z", "shell.execute_reply": "2025-03-25T05:43:04.423954Z" } }, "outputs": [], "source": [ "# Review gene identifiers to determine if they need mapping\n", "# The identifiers start with \"ILMN_\" which indicates they are Illumina probe IDs\n", "# These are not human gene symbols and will need to be mapped to gene symbols\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "366e0e3c", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "76c68b9a", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:43:04.425420Z", "iopub.status.busy": "2025-03-25T05:43:04.425319Z", "iopub.status.idle": "2025-03-25T05:43:05.350547Z", "shell.execute_reply": "2025-03-25T05:43:05.350160Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Examining SOFT file structure:\n", "Line 0: ^DATABASE = GeoMiame\n", "Line 1: !Database_name = Gene Expression Omnibus (GEO)\n", "Line 2: !Database_institute = NCBI NLM NIH\n", "Line 3: !Database_web_link = http://www.ncbi.nlm.nih.gov/geo\n", "Line 4: !Database_email = geo@ncbi.nlm.nih.gov\n", "Line 5: ^SERIES = GSE66843\n", "Line 6: !Series_title = A cell-based model unravels drivers for hepatocarcinogenesis and targets for clinical chemoprevention\n", "Line 7: !Series_geo_accession = GSE66843\n", "Line 8: !Series_status = Public on Jun 28 2021\n", "Line 9: !Series_submission_date = Mar 12 2015\n", "Line 10: !Series_last_update_date = Jun 29 2022\n", "Line 11: !Series_pubmed_id = 34535664\n", "Line 12: !Series_summary = This SuperSeries is composed of the SubSeries listed below.\n", "Line 13: !Series_overall_design = Refer to individual Series\n", "Line 14: !Series_type = Expression profiling by array\n", "Line 15: !Series_type = Expression profiling by high throughput sequencing\n", "Line 16: !Series_sample_id = GSM1633141\n", "Line 17: !Series_sample_id = GSM1633142\n", "Line 18: !Series_sample_id = GSM1633143\n", "Line 19: !Series_sample_id = GSM1633144\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene annotation preview:\n", "{'ID': ['ILMN_1343048', 'ILMN_1343049', 'ILMN_1343050', 'ILMN_1343052', 'ILMN_1343059'], 'Species': [nan, nan, nan, nan, nan], 'Source': [nan, nan, nan, nan, nan], 'Search_Key': [nan, nan, nan, nan, nan], 'Transcript': [nan, nan, nan, nan, nan], 'ILMN_Gene': [nan, nan, nan, nan, nan], 'Source_Reference_ID': [nan, nan, nan, nan, nan], 'RefSeq_ID': [nan, nan, nan, nan, nan], 'Unigene_ID': [nan, nan, nan, nan, nan], 'Entrez_Gene_ID': [nan, nan, nan, nan, nan], 'GI': [nan, nan, nan, nan, nan], 'Accession': [nan, nan, nan, nan, nan], 'Symbol': ['phage_lambda_genome', 'phage_lambda_genome', 'phage_lambda_genome:low', 'phage_lambda_genome:low', 'thrB'], 'Protein_Product': [nan, nan, nan, nan, 'thrB'], 'Probe_Id': [nan, nan, nan, nan, nan], 'Array_Address_Id': [5090180, 6510136, 7560739, 1450438, 1240647], 'Probe_Type': [nan, nan, nan, nan, nan], 'Probe_Start': [nan, nan, nan, nan, nan], 'SEQUENCE': ['GAATAAAGAACAATCTGCTGATGATCCCTCCGTGGATCTGATTCGTGTAA', 'CCATGTGATACGAGGGCGCGTAGTTTGCATTATCGTTTTTATCGTTTCAA', 'CCGACAGATGTATGTAAGGCCAACGTGCTCAAATCTTCATACAGAAAGAT', 'TCTGTCACTGTCAGGAAAGTGGTAAAACTGCAACTCAATTACTGCAATGC', 'CTTGTGCCTGAGCTGTCAAAAGTAGAGCACGTCGCCGAGATGAAGGGCGC'], 'Chromosome': [nan, nan, nan, nan, nan], 'Probe_Chr_Orientation': [nan, nan, nan, nan, nan], 'Probe_Coordinates': [nan, nan, nan, nan, nan], 'Cytoband': [nan, nan, nan, nan, nan], 'Definition': [nan, nan, nan, nan, nan], 'Ontology_Component': [nan, nan, nan, nan, nan], 'Ontology_Process': [nan, nan, nan, nan, nan], 'Ontology_Function': [nan, nan, nan, nan, nan], 'Synonyms': [nan, nan, nan, nan, nan], 'Obsolete_Probe_Id': [nan, nan, nan, nan, nan], 'GB_ACC': [nan, nan, nan, nan, nan]}\n" ] } ], "source": [ "# 1. Let's first examine the structure of the SOFT file before trying to parse it\n", "import gzip\n", "\n", "# Look at the first few lines of the SOFT file to understand its structure\n", "print(\"Examining SOFT file structure:\")\n", "try:\n", " with gzip.open(soft_file, 'rt') as file:\n", " # Read first 20 lines to understand the file structure\n", " for i, line in enumerate(file):\n", " if i < 20:\n", " print(f\"Line {i}: {line.strip()}\")\n", " else:\n", " break\n", "except Exception as e:\n", " print(f\"Error reading SOFT file: {e}\")\n", "\n", "# 2. Now let's try a more robust approach to extract the gene annotation\n", "# Instead of using the library function which failed, we'll implement a custom approach\n", "try:\n", " # First, look for the platform section which contains gene annotation\n", " platform_data = []\n", " with gzip.open(soft_file, 'rt') as file:\n", " in_platform_section = False\n", " for line in file:\n", " if line.startswith('^PLATFORM'):\n", " in_platform_section = True\n", " continue\n", " if in_platform_section and line.startswith('!platform_table_begin'):\n", " # Next line should be the header\n", " header = next(file).strip()\n", " platform_data.append(header)\n", " # Read until the end of the platform table\n", " for table_line in file:\n", " if table_line.startswith('!platform_table_end'):\n", " break\n", " platform_data.append(table_line.strip())\n", " break\n", " \n", " # If we found platform data, convert it to a DataFrame\n", " if platform_data:\n", " import pandas as pd\n", " import io\n", " platform_text = '\\n'.join(platform_data)\n", " gene_annotation = pd.read_csv(io.StringIO(platform_text), delimiter='\\t', \n", " low_memory=False, on_bad_lines='skip')\n", " print(\"\\nGene annotation preview:\")\n", " print(preview_df(gene_annotation))\n", " else:\n", " print(\"Could not find platform table in SOFT file\")\n", " \n", " # Try an alternative approach - extract mapping from other sections\n", " with gzip.open(soft_file, 'rt') as file:\n", " for line in file:\n", " if 'ANNOTATION information' in line or 'annotation information' in line:\n", " print(f\"Found annotation information: {line.strip()}\")\n", " if line.startswith('!Platform_title') or line.startswith('!platform_title'):\n", " print(f\"Platform title: {line.strip()}\")\n", " \n", "except Exception as e:\n", " print(f\"Error processing gene annotation: {e}\")\n" ] }, { "cell_type": "markdown", "id": "0fad6fbb", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "17a3d910", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:43:05.351961Z", "iopub.status.busy": "2025-03-25T05:43:05.351839Z", "iopub.status.idle": "2025-03-25T05:43:05.685527Z", "shell.execute_reply": "2025-03-25T05:43:05.685137Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Creating gene mapping from annotation data...\n", "Created gene mapping with 44837 rows\n", "Sample of gene mapping:\n", " ID Gene\n", "0 ILMN_1343048 phage_lambda_genome\n", "1 ILMN_1343049 phage_lambda_genome\n", "2 ILMN_1343050 phage_lambda_genome:low\n", "3 ILMN_1343052 phage_lambda_genome:low\n", "4 ILMN_1343059 thrB\n", "Proportion of probes with valid gene symbols: 44837/44837 (100.0%)\n", "\n", "Converting probe-level measurements to gene expression data...\n", "Created gene expression data with 21125 genes\n", "First few genes:\n", "Index(['A1BG', 'A1CF', 'A26C3', 'A2BP1', 'A2LD1', 'A2M', 'A2ML1', 'A3GALT2',\n", " 'A4GALT', 'A4GNT'],\n", " dtype='object', name='Gene')\n", "Gene expression matrix shape: (21125, 17)\n", "\n", "Preview of gene expression data:\n", " GSM1633236 GSM1633237 GSM1633238 GSM1633239 GSM1633240\n", "Gene \n", "A1BG 175.902881 175.467437 185.163824 175.411354 181.091704\n", "A1CF 2058.146767 1601.515698 1713.037609 1508.079221 1556.390170\n", "A26C3 264.005316 262.772229 258.887037 258.446203 256.012300\n", "A2BP1 253.386795 253.606930 254.187523 254.727873 256.852300\n", "A2LD1 95.837982 105.912588 85.844743 95.409101 104.229355\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data saved to ../../output/preprocess/Hepatitis/gene_data/GSE66843.csv\n" ] } ], "source": [ "# 1. Determine the column names for probe IDs and gene symbols from the annotation preview\n", "# From the annotation preview, we can see:\n", "# - 'ID' contains the gene identifiers (ILMN_*) which match the gene expression data\n", "# - 'Symbol' contains the gene symbols we want to map to\n", "\n", "# 2. Get a gene mapping dataframe from the annotation\n", "print(\"Creating gene mapping from annotation data...\")\n", "try:\n", " # Get gene mapping by selecting ID and Symbol columns from the gene annotation\n", " gene_mapping = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Symbol')\n", " print(f\"Created gene mapping with {len(gene_mapping)} rows\")\n", " print(\"Sample of gene mapping:\")\n", " print(gene_mapping.head())\n", " \n", " # Check proportion of IDs that have gene symbols\n", " valid_symbols = gene_mapping['Gene'].notnull().sum()\n", " total_rows = len(gene_mapping)\n", " print(f\"Proportion of probes with valid gene symbols: {valid_symbols}/{total_rows} ({valid_symbols/total_rows:.1%})\")\n", " \n", " # 3. Convert probe-level data to gene expression data\n", " print(\"\\nConverting probe-level measurements to gene expression data...\")\n", " gene_data = apply_gene_mapping(gene_data, gene_mapping)\n", " print(f\"Created gene expression data with {len(gene_data)} genes\")\n", " print(\"First few genes:\")\n", " print(gene_data.index[:10])\n", " \n", " # Check gene_data dimensions\n", " print(f\"Gene expression matrix shape: {gene_data.shape}\")\n", " \n", " # Preview a small sample of the gene data\n", " print(\"\\nPreview of gene expression data:\")\n", " sample_genes = gene_data.iloc[:5, :5]\n", " print(sample_genes)\n", " \n", " # Save the gene data\n", " # Create directory if it doesn't exist\n", " os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", " \n", " # Save the gene expression data\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: {e}\")\n", " is_gene_available = False\n" ] }, { "cell_type": "markdown", "id": "c8e985e7", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "90b7dff0", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:43:05.687046Z", "iopub.status.busy": "2025-03-25T05:43:05.686912Z", "iopub.status.idle": "2025-03-25T05:43:13.342008Z", "shell.execute_reply": "2025-03-25T05:43:13.341427Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape before normalization: (21125, 17)\n", "Gene data shape after normalization: (19956, 17)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data saved to ../../output/preprocess/Hepatitis/gene_data/GSE66843.csv\n", "Clinical data saved to ../../output/preprocess/Hepatitis/clinical_data/GSE66843.csv\n", "Linked data shape: (17, 19957)\n", "\n", "Handling missing values...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "After missing value handling, linked data shape: (17, 19957)\n", "\n", "Evaluating feature bias...\n", "For the feature 'Hepatitis', the least common label is '0.0' with 8 occurrences. This represents 47.06% of the dataset.\n", "The distribution of the feature 'Hepatitis' in this dataset is fine.\n", "\n", "Trait bias evaluation result: False\n", "\n", "Dataset usability: True\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data saved to ../../output/preprocess/Hepatitis/GSE66843.csv\n" ] } ], "source": [ "# 1. Normalize gene symbols and extract from step 3 and 6\n", "# Load the gene expression data (already loaded from Step 6)\n", "print(f\"Gene data shape before normalization: {gene_data.shape}\")\n", "\n", "try:\n", " # Normalize gene symbols using the NCBI Gene database information\n", " normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", " \n", " if normalized_gene_data.empty:\n", " print(\"Normalization resulted in empty dataframe. Using original gene data instead.\")\n", " normalized_gene_data = gene_data\n", " \n", " print(f\"Gene data shape after normalization: {normalized_gene_data.shape}\")\n", " \n", " # Save the normalized gene data to the output 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 data saved to {out_gene_data_file}\")\n", "except Exception as e:\n", " print(f\"Error normalizing gene data: {e}. Using original gene data instead.\")\n", " normalized_gene_data = gene_data\n", " # Save the original gene data if normalization fails\n", " os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", " normalized_gene_data.to_csv(out_gene_data_file)\n", "\n", "# 2. Link clinical and genetic data\n", "# Use the trait_row identified in Step 2 (trait_row = 1) to extract trait data\n", "is_trait_available = trait_row is not None\n", "\n", "if is_trait_available:\n", " # Extract clinical features using the function and conversion methods from Step 2\n", " clinical_features = 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", " # Save clinical features\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", " # Link clinical and genetic data\n", " linked_data = geo_link_clinical_genetic_data(clinical_features, normalized_gene_data)\n", " print(f\"Linked data shape: {linked_data.shape}\")\n", "else:\n", " # Create a minimal dataframe with just the trait column\n", " linked_data = pd.DataFrame({trait: [np.nan]})\n", " print(\"No trait data available, creating minimal dataframe for validation.\")\n", "\n", "# 3. Handle missing values in the linked data\n", "if is_trait_available:\n", " print(\"\\nHandling missing values...\")\n", " linked_data = handle_missing_values(linked_data, trait)\n", " print(f\"After missing value handling, linked data shape: {linked_data.shape}\")\n", "\n", "# 4. Determine whether trait and demographic features are biased\n", "if is_trait_available and not linked_data.empty and len(linked_data.columns) > 1:\n", " print(\"\\nEvaluating feature bias...\")\n", " is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n", " print(f\"Trait bias evaluation result: {is_biased}\")\n", "else:\n", " is_biased = False\n", " print(\"Skipping bias evaluation due to insufficient data.\")\n", "\n", "# 5. Final validation and save metadata\n", "note = \"\"\n", "if not is_trait_available:\n", " note = f\"Dataset contains gene expression data but no {trait} measurements.\"\n", "elif is_biased:\n", " note = f\"Dataset contains {trait} data but its distribution is severely biased.\"\n", "\n", "# Validate and save cohort info\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", "# 6. Save the linked data if usable\n", "print(f\"\\nDataset usability: {is_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(f\"Dataset is not usable for {trait} association studies. Data not saved.\")" ] } ], "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 }