{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "ad2b6e1a", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:05:13.811433Z", "iopub.status.busy": "2025-03-25T08:05:13.811328Z", "iopub.status.idle": "2025-03-25T08:05:13.978687Z", "shell.execute_reply": "2025-03-25T08:05:13.978340Z" } }, "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 = \"Metabolic_Rate\"\n", "cohort = \"GSE101492\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Metabolic_Rate\"\n", "in_cohort_dir = \"../../input/GEO/Metabolic_Rate/GSE101492\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Metabolic_Rate/GSE101492.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Metabolic_Rate/gene_data/GSE101492.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Metabolic_Rate/clinical_data/GSE101492.csv\"\n", "json_path = \"../../output/preprocess/Metabolic_Rate/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "4f61cad7", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "db3f449e", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:05:13.980152Z", "iopub.status.busy": "2025-03-25T08:05:13.980012Z", "iopub.status.idle": "2025-03-25T08:05:14.215541Z", "shell.execute_reply": "2025-03-25T08:05:14.215191Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Files in the directory:\n", "['GSE101492_family.soft.gz', 'GSE101492_series_matrix.txt.gz']\n", "SOFT file: ../../input/GEO/Metabolic_Rate/GSE101492/GSE101492_family.soft.gz\n", "Matrix file: ../../input/GEO/Metabolic_Rate/GSE101492/GSE101492_series_matrix.txt.gz\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"LONG NON-CODING RNAs ASSOCIATED WITH METABOLIC TRAITS IN HUMAN WHITE ADIPOSE TISSUE\"\n", "!Series_summary\t\"The aim of this study was to identify novel long noncoding RNAs (lncRNAs) that are differentially expressed in the subcutaneous region either in obesity or insulin resistance.\"\n", "!Series_summary\t\"A number of novel lncRNAs were differentially expressed in the subcutaneous region either in obesity or insulin resistance. Two lncRNAs (termed here as adipocyte specific insulin resistance related lncRNAs (ADLNRIs), ADLNRI 1 and ADLNRI 2) were influenced by both conditions and enriched in adipocytes. Knockdown of either by antisense oligonucleotides in fat cellsadipocytes altered lipolysis and adiponectin secretion, respectively.\"\n", "!Series_overall_design\t\"The 80 women included in this study were selected from the extremes of insulin sensitivity as measured by homeostasis model assessment of IR (HOMAIR) among 220 obese women who participated in a clinical trial on the effect of bariatric surgery (NCT01785134 at www.clinicaltrials.gov). All sampling and measurements were performed before or during bariatric surgery (laparoscopic gastric bypass). Participants were investigated at 8 AM after an overnight fast. Insulin sensitivity was assessed by HOMAIR and was calculated from fasting measures of glucose and insulin. High HOMAIR values indicate IR. The 40 women with the highest HOMAIR values and the 40 women with the lowest values were selected for inclusion in the present study. Differential gene expression analysis was conducted at the gene level using Limma, selecting for genes with a false discovery rate of <0.05\"\n", "Sample Characteristics Dictionary:\n", "{0: ['suject status: obese'], 1: ['gender: female'], 2: ['age: 39', 'age: 28', 'age: 42', 'age: 30', 'age: 37', 'age: 36', 'age: 33', 'age: 27', 'age: 43', 'age: 44', 'age: 25', 'age: 35', 'age: 40', 'age: 29', 'age: 41', 'age: 34', 'age: 31', 'age: 38', 'age: 26', 'age: 32', 'age: 45'], 3: ['insulin sensitivity: insulin sensitive', 'insulin sensitivity: insulin resistant'], 4: ['tissue: subcutaneous white adipose tissue']}\n" ] } ], "source": [ "# 1. Check what files are actually in the directory\n", "import os\n", "print(\"Files in the directory:\")\n", "files = os.listdir(in_cohort_dir)\n", "print(files)\n", "\n", "# 2. Find appropriate files with more flexible pattern matching\n", "soft_file = None\n", "matrix_file = None\n", "\n", "for file in files:\n", " file_path = os.path.join(in_cohort_dir, file)\n", " # Look for files that might contain SOFT or matrix data with various possible extensions\n", " if 'soft' in file.lower() or 'family' in file.lower() or file.endswith('.soft.gz'):\n", " soft_file = file_path\n", " if 'matrix' in file.lower() or file.endswith('.txt.gz') or file.endswith('.tsv.gz'):\n", " matrix_file = file_path\n", "\n", "if not soft_file:\n", " print(\"Warning: Could not find a SOFT file. Using the first .gz file as fallback.\")\n", " gz_files = [f for f in files if f.endswith('.gz')]\n", " if gz_files:\n", " soft_file = os.path.join(in_cohort_dir, gz_files[0])\n", "\n", "if not matrix_file:\n", " print(\"Warning: Could not find a matrix file. Using the second .gz file as fallback if available.\")\n", " gz_files = [f for f in files if f.endswith('.gz')]\n", " if len(gz_files) > 1 and soft_file != os.path.join(in_cohort_dir, gz_files[1]):\n", " matrix_file = os.path.join(in_cohort_dir, gz_files[1])\n", " elif len(gz_files) == 1 and not soft_file:\n", " matrix_file = os.path.join(in_cohort_dir, gz_files[0])\n", "\n", "print(f\"SOFT file: {soft_file}\")\n", "print(f\"Matrix file: {matrix_file}\")\n", "\n", "# 3. Read files if found\n", "if soft_file and matrix_file:\n", " # 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", " \n", " try:\n", " background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n", " \n", " # Obtain the sample characteristics dictionary from the clinical dataframe\n", " sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n", " \n", " # 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", " except Exception as e:\n", " print(f\"Error processing files: {e}\")\n", " # Try swapping files if first attempt fails\n", " print(\"Trying to swap SOFT and matrix files...\")\n", " temp = soft_file\n", " soft_file = matrix_file\n", " matrix_file = temp\n", " try:\n", " background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n", " sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n", " print(\"Background Information:\")\n", " print(background_info)\n", " print(\"Sample Characteristics Dictionary:\")\n", " print(sample_characteristics_dict)\n", " except Exception as e:\n", " print(f\"Still error after swapping: {e}\")\n", "else:\n", " print(\"Could not find necessary files for processing.\")\n" ] }, { "cell_type": "markdown", "id": "f6b48238", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "227ffb58", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:05:14.217434Z", "iopub.status.busy": "2025-03-25T08:05:14.217293Z", "iopub.status.idle": "2025-03-25T08:05:14.792810Z", "shell.execute_reply": "2025-03-25T08:05:14.792428Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Preview of clinical features: {0: [nan, nan], 1: [nan, nan], 2: [nan, nan], 3: [nan, nan], 4: [nan, nan], 5: [nan, nan], 6: [nan, nan], 7: [nan, nan], 8: [nan, nan], 9: [nan, nan], 10: [nan, nan], 11: [nan, nan], 12: [nan, nan], 13: [nan, nan], 14: [nan, nan], 15: [nan, nan], 16: [nan, nan], 17: [nan, nan], 18: [nan, nan], 19: [nan, nan], 20: [nan, nan], 21: [nan, nan], 22: [nan, nan], 23: [nan, nan], 24: [nan, nan], 25: [nan, nan], 26: [nan, nan], 27: [nan, nan], 28: [nan, nan], 29: [nan, nan], 30: [nan, nan], 31: [nan, nan], 32: [nan, nan], 33: [nan, nan], 34: [nan, nan], 35: [nan, nan], 36: [nan, nan], 37: [nan, nan], 38: [nan, nan], 39: [nan, nan], 40: [nan, nan], 41: [nan, nan], 42: [nan, nan], 43: [nan, nan], 44: [nan, nan], 45: [nan, nan], 46: [nan, nan], 47: [nan, nan], 48: [nan, nan], 49: [nan, nan], 50: [nan, nan], 51: [nan, nan], 52: [nan, nan], 53: [nan, nan], 54: [nan, nan], 55: [nan, nan], 56: [nan, nan], 57: [nan, nan], 58: [nan, nan], 59: [nan, nan], 60: [nan, nan], 61: [nan, nan], 62: [nan, nan], 63: [nan, nan], 64: [nan, nan], 65: [nan, nan], 66: [nan, nan], 67: [nan, nan], 68: [nan, nan], 69: [nan, nan], 70: [nan, nan], 71: [nan, nan], 72: [nan, nan], 73: [nan, nan], 74: [nan, nan], 75: [nan, nan], 76: [nan, nan], 77: [nan, nan], 78: [nan, nan], 79: [nan, nan], 80: [nan, nan]}\n", "Clinical features saved to ../../output/preprocess/Metabolic_Rate/clinical_data/GSE101492.csv\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "/tmp/ipykernel_70236/1821478240.py:84: DtypeWarning: Columns (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80) have mixed types. Specify dtype option on import or set low_memory=False.\n", " clinical_data = pd.read_csv(\n" ] } ], "source": [ "import pandas as pd\n", "import os\n", "import numpy as np\n", "from typing import Optional, Callable, Dict, Any\n", "import json\n", "import gzip\n", "\n", "# 1. Gene Expression Data Availability\n", "# Based on the series title and summary, this is a study on lncRNAs in white adipose tissue\n", "# lncRNAs are gene expression data, not miRNA or methylation data\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "# From the Sample Characteristics Dictionary:\n", "# Key 3 shows 'insulin sensitivity: insulin sensitive' or 'insulin resistant' - this relates to metabolic rate\n", "# Key 2 shows age values\n", "# Key 1 shows gender, but it's constant (all female)\n", "\n", "trait_row = 3 # insulin sensitivity is related to metabolic rate\n", "age_row = 2 # age data is available\n", "gender_row = None # all subjects are female, so this is a constant feature\n", "\n", "# 2.2 Data Type Conversion Functions\n", "def convert_trait(value: str) -> int:\n", " \"\"\"Convert insulin sensitivity to binary values for metabolic rate.\n", " \n", " Insulin resistant (higher HOMAIR) = 1 (indicates impaired metabolic rate)\n", " Insulin sensitive (lower HOMAIR) = 0 (indicates normal metabolic rate)\n", " \"\"\"\n", " if not isinstance(value, str):\n", " return None\n", " \n", " value = value.lower()\n", " if \"insulin resistant\" in value:\n", " return 1\n", " elif \"insulin sensitive\" in value:\n", " return 0\n", " else:\n", " return None\n", "\n", "def convert_age(value: str) -> int:\n", " \"\"\"Convert age string to integer value.\"\"\"\n", " if not isinstance(value, str):\n", " return None\n", " \n", " if \"age:\" in value:\n", " try:\n", " return int(value.split(\"age:\")[1].strip())\n", " except (ValueError, IndexError):\n", " return None\n", " return None\n", "\n", "def convert_gender(value: str) -> Optional[int]:\n", " \"\"\"Convert gender to binary (0 for female, 1 for male).\"\"\"\n", " # Not used in this dataset as all subjects are female\n", " if not isinstance(value, str):\n", " return None\n", " \n", " value = value.lower()\n", " if \"female\" in value:\n", " return 0\n", " elif \"male\" in value:\n", " return 1\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Determine trait data availability\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", "if trait_row is not None:\n", " # Load the clinical data from the matrix file properly\n", " # Read the matrix file using pandas with proper handling of gzipped file\n", " clinical_data = pd.read_csv(\n", " os.path.join(in_cohort_dir, \"GSE101492_series_matrix.txt.gz\"), \n", " compression='gzip', \n", " sep='\\t', \n", " comment='!', \n", " header=None\n", " )\n", " \n", " # Extract clinical features using the provided function\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 and convert_gender are not provided since all subjects are female\n", " )\n", " \n", " # Preview extracted clinical features\n", " preview = preview_df(clinical_features_df)\n", " print(\"Preview of clinical features:\", 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 extracted clinical features to CSV\n", " clinical_features_df.to_csv(out_clinical_data_file, index=False)\n", " print(f\"Clinical features saved to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "07bce2e0", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "c8a1f9df", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:05:14.794709Z", "iopub.status.busy": "2025-03-25T08:05:14.794561Z", "iopub.status.idle": "2025-03-25T08:05:15.187914Z", "shell.execute_reply": "2025-03-25T08:05:15.187533Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "This appears to be a SuperSeries. Looking at the SOFT file to find potential subseries:\n", "No subseries references found in the first 1000 lines of the SOFT file.\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene data extraction result:\n", "Number of rows: 70523\n", "First 20 gene/probe identifiers:\n", "Index(['18670005', '18670007', '18670009', '18670011', '18670020', '18670022',\n", " '18670023', '18670027', '18670028', '18670032', '18670033', '18670036',\n", " '18670038', '18670039', '18670041', '18670049', '18670051', '18670053',\n", " '18670054', '18670056'],\n", " dtype='object', name='ID')\n" ] } ], "source": [ "# 1. First get the path to the soft and matrix files\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# 2. Looking more carefully at the background information\n", "# This is a SuperSeries which doesn't contain direct gene expression data\n", "# Need to investigate the soft file to find the subseries\n", "print(\"This appears to be a SuperSeries. Looking at the SOFT file to find potential subseries:\")\n", "\n", "# Open the SOFT file to try to identify subseries\n", "with gzip.open(soft_file, 'rt') as f:\n", " subseries_lines = []\n", " for i, line in enumerate(f):\n", " if 'Series_relation' in line and 'SuperSeries of' in line:\n", " subseries_lines.append(line.strip())\n", " if i > 1000: # Limit search to first 1000 lines\n", " break\n", "\n", "# Display the subseries found\n", "if subseries_lines:\n", " print(\"Found potential subseries references:\")\n", " for line in subseries_lines:\n", " print(line)\n", "else:\n", " print(\"No subseries references found in the first 1000 lines of the SOFT file.\")\n", "\n", "# Despite trying to extract gene data, we expect it might fail because this is a SuperSeries\n", "try:\n", " gene_data = get_genetic_data(matrix_file)\n", " print(\"\\nGene data extraction result:\")\n", " print(\"Number of rows:\", len(gene_data))\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", " print(\"This confirms the dataset is a SuperSeries without direct gene expression data.\")\n" ] }, { "cell_type": "markdown", "id": "019d92f6", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "64818bda", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:05:15.189896Z", "iopub.status.busy": "2025-03-25T08:05:15.189776Z", "iopub.status.idle": "2025-03-25T08:05:15.191681Z", "shell.execute_reply": "2025-03-25T08:05:15.191398Z" } }, "outputs": [], "source": [ "# Analyzing the gene identifiers\n", "# The identifiers like '18670005' appear to be probe IDs or array-specific identifiers \n", "# rather than standard human gene symbols (which would look like 'BRCA1', 'TP53', etc.)\n", "# These numeric identifiers need to be mapped to standard gene symbols for meaningful analysis\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "64c3ed10", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "db5fef56", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:05:15.193422Z", "iopub.status.busy": "2025-03-25T08:05:15.193284Z", "iopub.status.idle": "2025-03-25T08:05:24.393481Z", "shell.execute_reply": "2025-03-25T08:05:24.393095Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene annotation preview:\n", "{'ID': ['18670005', '18670007', '18670009', '18670011', '18670020'], 'probeset_id': ['18670005', '18670007', '18670009', '18670011', '18670020'], 'seqname': ['---', '---', '---', '---', '---'], 'strand': ['---', '---', '---', '---', '---'], 'start': ['---', '---', '---', '---', '---'], 'stop': ['---', '---', '---', '---', '---'], 'total_probes': [3.0, 1.0, 2.0, 2.0, 2.0], 'gene_assignment': ['--- // --- // Positive Housekeeping Controls - Probeset Type: normgene->exon // --- // ---', '--- // --- // Positive Housekeeping Controls - Probeset Type: normgene->exon // --- // ---', '--- // --- // Positive Housekeeping Controls - Probeset Type: normgene->exon // --- // ---', '--- // --- // Positive Housekeeping Controls - Probeset Type: normgene->exon // --- // ---', '--- // --- // Positive Housekeeping Controls - Probeset Type: normgene->exon // --- // ---'], 'mrna_assignment': ['---', '---', '---', '---', '---'], 'swissprot': ['---', '---', '---', '---', '---'], 'unigene': ['---', '---', '---', '---', '---'], 'category': ['normgene->exon', 'normgene->exon', 'normgene->exon', 'normgene->exon', 'normgene->exon'], 'locus type': ['normgene->exon', 'normgene->exon', 'normgene->exon', 'normgene->exon', 'normgene->exon'], 'notes': ['---', '---', '---', '---', '---'], 'SPOT_ID': ['normgene->exon', 'normgene->exon', 'normgene->exon', 'normgene->exon', 'normgene->exon']}\n" ] } ], "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. Use the 'preview_df' function from the library to preview the data and print out the results.\n", "print(\"Gene annotation preview:\")\n", "print(preview_df(gene_annotation))\n" ] }, { "cell_type": "markdown", "id": "2f838eed", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "5d44ca0b", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:05:24.395364Z", "iopub.status.busy": "2025-03-25T08:05:24.395238Z", "iopub.status.idle": "2025-03-25T08:06:09.512763Z", "shell.execute_reply": "2025-03-25T08:06:09.512371Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Column names in gene annotation dataframe:\n", "['ID', 'probeset_id', 'seqname', 'strand', 'start', 'stop', 'total_probes', 'gene_assignment', 'mrna_assignment', 'swissprot', 'unigene', 'category', 'locus type', 'notes', 'SPOT_ID']\n", "\n", "Sample rows with all columns from gene annotation dataframe:\n", " ID probeset_id seqname strand start stop total_probes \\\n", "0 18670005 18670005 --- --- --- --- 3.0 \n", "1 18670007 18670007 --- --- --- --- 1.0 \n", "2 18670009 18670009 --- --- --- --- 2.0 \n", "3 18670011 18670011 --- --- --- --- 2.0 \n", "4 18670020 18670020 --- --- --- --- 2.0 \n", "\n", " gene_assignment mrna_assignment \\\n", "0 --- // --- // Positive Housekeeping Controls -... --- \n", "1 --- // --- // Positive Housekeeping Controls -... --- \n", "2 --- // --- // Positive Housekeeping Controls -... --- \n", "3 --- // --- // Positive Housekeeping Controls -... --- \n", "4 --- // --- // Positive Housekeeping Controls -... --- \n", "\n", " swissprot unigene category locus type notes SPOT_ID \n", "0 --- --- normgene->exon normgene->exon --- normgene->exon \n", "1 --- --- normgene->exon normgene->exon --- normgene->exon \n", "2 --- --- normgene->exon normgene->exon --- normgene->exon \n", "3 --- --- normgene->exon normgene->exon --- normgene->exon \n", "4 --- --- normgene->exon normgene->exon --- normgene->exon \n", "\n", "Sampling gene_assignment column (first 5 non-null values):\n", "--- // --- // Positive Housekeeping Controls - Probeset Type: normgene->exon // --- // ---\n", "--- // --- // Positive Housekeeping Controls - Probeset Type: normgene->exon // --- // ---\n", "--- // --- // Positive Housekeeping Controls - Probeset Type: normgene->exon // --- // ---\n", "--- // --- // Positive Housekeeping Controls - Probeset Type: normgene->exon // --- // ---\n", "--- // --- // Positive Housekeeping Controls - Probeset Type: normgene->exon // --- // ---\n", "\n", "Sampling mrna_assignment column (first 5 non-null values):\n", "---\n", "---\n", "---\n", "---\n", "---\n", "\n", "Sampling swissprot column (first 5 non-null values):\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "---\n", "---\n", "---\n", "---\n", "---\n", "\n", "Sampling unigene column (first 5 non-null values):\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "---\n", "---\n", "---\n", "---\n", "---\n", "\n", "Sampling rows in the middle of the dataframe:\n", " ID gene_assignment\n", "2856336 TC0X000949.hg.1 NaN\n", "2856337 TC0X000950.hg.1 NaN\n", "2856338 TC0X000951.hg.1 NaN\n", "2856339 TC0X000952.hg.1 NaN\n", "2856340 TC0X000953.hg.1 NaN\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Number of rows with potential gene mapping: 67362\n", "Number of rows after exploding Gene column: 100032\n", "\n", "Preview of gene mapping dataframe:\n", "{'ID': ['TC01000001.hg.1', 'TC01000001.hg.1', 'TC01000002.hg.1', 'TC01000002.hg.1', 'TC01000003.hg.1'], 'Gene': ['NR_046018', 'NR_046018', 'ENST00000408384', 'ENST00000408384', 'NM_001005484']}\n", "\n", "Final number of mappable probes: 100032\n", "\n", "Applying gene mapping...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Number of genes after mapping: 182\n", "First 5 genes:\n", "Index(['BC000988', 'BC001023', 'BC001499', 'BC001846', 'BC001959'], dtype='object', name='Gene')\n", "\n", "Normalizing gene symbols...\n", "Number of genes after normalization: 0\n", "\n", "Gene expression data saved to: ../../output/preprocess/Metabolic_Rate/gene_data/GSE101492.csv\n" ] } ], "source": [ "# 1. Examine the gene annotation dataframe more comprehensively to find gene identifiers\n", "print(\"Column names in gene annotation dataframe:\")\n", "print(gene_annotation.columns.tolist())\n", "\n", "# Let's look at more columns that might contain gene information\n", "sample_rows = gene_annotation.head(5)\n", "print(\"\\nSample rows with all columns from gene annotation dataframe:\")\n", "print(sample_rows)\n", "\n", "# Looking closer at potential gene-containing columns\n", "potential_gene_columns = ['gene_assignment', 'mrna_assignment', 'swissprot', 'unigene']\n", "for col in potential_gene_columns:\n", " if col in gene_annotation.columns:\n", " print(f\"\\nSampling {col} column (first 5 non-null values):\")\n", " sample_values = gene_annotation[col].dropna().head(5).tolist()\n", " for val in sample_values:\n", " print(val)\n", "\n", "# Let's look at a different part of the dataframe\n", "print(\"\\nSampling rows in the middle of the dataframe:\")\n", "mid_index = len(gene_annotation) // 2\n", "mid_sample = gene_annotation.iloc[mid_index:mid_index+5]\n", "print(mid_sample[['ID', 'gene_assignment']])\n", "\n", "# Based on our examination, we need to extract gene information differently\n", "# We'll try a more comprehensive approach to identify gene symbols\n", "def extract_genes_from_multiple_sources(row):\n", " \"\"\"Extract gene symbols from various columns in the annotation\"\"\"\n", " # Initialize with an empty list\n", " genes = []\n", " \n", " # Try gene_assignment first\n", " if isinstance(row.get('gene_assignment'), str):\n", " assignment = row['gene_assignment']\n", " if assignment != '---' and 'Housekeeping Controls' not in assignment:\n", " parts = assignment.split('//')\n", " if len(parts) > 0 and parts[0].strip() != '---':\n", " genes.append(parts[0].strip())\n", " \n", " # Try other columns if available\n", " if isinstance(row.get('mrna_assignment'), str) and row['mrna_assignment'] != '---':\n", " mRNA_id = row['mrna_assignment'].split('//')[0].strip()\n", " if mRNA_id and mRNA_id != '---':\n", " genes.append(mRNA_id)\n", " \n", " # Use the ID itself if it appears to be a gene identifier\n", " if isinstance(row.get('ID'), str) and (row['ID'].startswith('NM_') or row['ID'].startswith('NR_')):\n", " genes.append(row['ID'])\n", " \n", " # Combine all found genes\n", " return genes if genes else None\n", "\n", "# Apply our custom function to extract gene symbols\n", "gene_annotation['Gene'] = gene_annotation.apply(extract_genes_from_multiple_sources, axis=1)\n", "\n", "# Create gene mapping dataframe\n", "valid_mapping = gene_annotation[['ID', 'Gene']].dropna()\n", "print(f\"\\nNumber of rows with potential gene mapping: {len(valid_mapping)}\")\n", "\n", "# Since 'Gene' might contain lists, we need to explode it\n", "mapping_exploded = valid_mapping.explode('Gene')\n", "print(f\"Number of rows after exploding Gene column: {len(mapping_exploded)}\")\n", "print(\"\\nPreview of gene mapping dataframe:\")\n", "print(preview_df(mapping_exploded))\n", "\n", "# 2. Create final gene mapping dataframe\n", "gene_mapping = mapping_exploded[['ID', 'Gene']].copy()\n", "print(f\"\\nFinal number of mappable probes: {len(gene_mapping)}\")\n", "\n", "# 3. Apply the gene mapping to convert probe-level data to gene expression data\n", "print(\"\\nApplying gene mapping...\")\n", "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n", "print(f\"Number of genes after mapping: {len(gene_data)}\")\n", "if len(gene_data) > 0:\n", " print(\"First 5 genes:\")\n", " print(gene_data.index[:5])\n", "else:\n", " print(\"Warning: No genes were mapped successfully.\")\n", "\n", "# Normalize gene symbols to ensure consistency\n", "print(\"\\nNormalizing gene symbols...\")\n", "gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"Number of genes after normalization: {len(gene_data)}\")\n", "if len(gene_data) > 0:\n", " print(\"First 5 normalized genes:\")\n", " print(gene_data.index[:5])\n", "\n", "# Save the gene expression data\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\"\\nGene expression data saved to: {out_gene_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "67a6222a", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "482547b1", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:06:09.514643Z", "iopub.status.busy": "2025-03-25T08:06:09.514529Z", "iopub.status.idle": "2025-03-25T08:06:09.830904Z", "shell.execute_reply": "2025-03-25T08:06:09.830364Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Shape of gene data after normalization: (0, 80)\n", "Saved normalized gene data to ../../output/preprocess/Metabolic_Rate/gene_data/GSE101492.csv\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Sample characteristics dictionary:\n", "{0: ['suject status: obese'], 1: ['gender: female'], 2: ['age: 39', 'age: 28', 'age: 42', 'age: 30', 'age: 37', 'age: 36', 'age: 33', 'age: 27', 'age: 43', 'age: 44', 'age: 25', 'age: 35', 'age: 40', 'age: 29', 'age: 41', 'age: 34', 'age: 31', 'age: 38', 'age: 26', 'age: 32', 'age: 45'], 3: ['insulin sensitivity: insulin sensitive', 'insulin sensitivity: insulin resistant'], 4: ['tissue: subcutaneous white adipose tissue']}\n", "Clinical data preview:\n", "{'Metabolic_Rate': [nan, nan, nan, nan, nan], 'Age': [39.0, 28.0, 42.0, 30.0, 42.0], 'Gender': [1.0, 1.0, 1.0, 1.0, 1.0]}\n", "Saved clinical data to ../../output/preprocess/Metabolic_Rate/clinical_data/GSE101492.csv\n", "Shape of linked data: (80, 3)\n", "Shape of linked data after handling missing values: (0, 2)\n", "Quartiles for 'Metabolic_Rate':\n", " 25%: nan\n", " 50% (Median): nan\n", " 75%: nan\n", "Min: nan\n", "Max: nan\n", "The distribution of the feature 'Metabolic_Rate' in this dataset is fine.\n", "\n", "Quartiles for 'Age':\n", " 25%: nan\n", " 50% (Median): nan\n", " 75%: nan\n", "Min: nan\n", "Max: nan\n", "The distribution of the feature 'Age' in this dataset is fine.\n", "\n", "Abnormality detected in the cohort: GSE101492. Preprocessing failed.\n", "A new JSON file was created at: ../../output/preprocess/Metabolic_Rate/cohort_info.json\n", "Dataset validation failed. Final linked data not saved.\n" ] } ], "source": [ "# 1. Normalize gene symbols in the gene expression data\n", "gene_data_normalized = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"Shape of gene data after normalization: {gene_data_normalized.shape}\")\n", "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", "gene_data_normalized.to_csv(out_gene_data_file)\n", "print(f\"Saved normalized gene data to {out_gene_data_file}\")\n", "\n", "# 2. Re-examine the clinical data from the matrix file\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "background_info, clinical_data = get_background_and_clinical_data(matrix_file)\n", "\n", "# Print out the sample characteristics to verify available rows\n", "characteristics_dict = get_unique_values_by_row(clinical_data)\n", "print(\"Sample characteristics dictionary:\")\n", "print(characteristics_dict)\n", "\n", "# Define conversion functions for the clinical features based on the actual data\n", "def convert_trait(value):\n", " \"\"\"Convert treatment group to binary based on lycopene level (low=0, high=1).\"\"\"\n", " if not isinstance(value, str):\n", " return None\n", " \n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip().lower()\n", " \n", " if 'high lycopene' in value:\n", " return 1.0 # High lycopene\n", " elif 'low lycopene' in value:\n", " return 0.0 # Low lycopene\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age data to continuous values.\"\"\"\n", " if not isinstance(value, str):\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 (female=0, male=1).\"\"\"\n", " if not isinstance(value, str):\n", " return None\n", " \n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip().lower()\n", " \n", " if 'male' in value:\n", " return 1.0\n", " elif 'female' in value:\n", " return 0.0\n", " else:\n", " return None\n", "\n", "# Create the clinical dataframe using the correct row indices based on sample characteristics\n", "try:\n", " # Row 3 contains treatment group (high/low lycopene) - this is our trait of interest\n", " # Row 2 contains age information\n", " # Row 1 contains gender information\n", " clinical_df = geo_select_clinical_features(\n", " clinical_data,\n", " trait=\"Metabolic_Rate\", # Using this as the trait name as per variable definition\n", " trait_row=3, # Treatment group as the trait (based on lycopene levels)\n", " convert_trait=convert_trait,\n", " gender_row=1, # Gender information is available in row 1\n", " convert_gender=convert_gender,\n", " age_row=2, # Age information is available in row 2\n", " convert_age=convert_age\n", " )\n", " \n", " print(\"Clinical data preview:\")\n", " print(preview_df(clinical_df.T)) # Transpose for better viewing\n", " \n", " # Save the clinical data\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " clinical_df.to_csv(out_clinical_data_file)\n", " print(f\"Saved clinical data to {out_clinical_data_file}\")\n", " \n", " # 3. Link clinical and genetic data\n", " linked_data = geo_link_clinical_genetic_data(clinical_df, gene_data_normalized)\n", " print(f\"Shape of linked data: {linked_data.shape}\")\n", " \n", " # 4. Handle missing values in the linked data\n", " linked_data_cleaned = handle_missing_values(linked_data, 'Metabolic_Rate')\n", " print(f\"Shape of linked data after handling missing values: {linked_data_cleaned.shape}\")\n", " \n", " # 5. Check if the trait and demographic features are biased\n", " is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data_cleaned, 'Metabolic_Rate')\n", " \n", " # 6. Validate the dataset and save cohort information\n", " note = \"Dataset contains gene expression data from a study examining the effects of carotenoid-rich vegetables on metabolic syndrome in obese Japanese men. The trait variable is treatment group based on lycopene levels (0=Low lycopene, 1=High lycopene).\"\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_trait_biased,\n", " df=unbiased_linked_data,\n", " note=note\n", " )\n", " \n", " # 7. Save the linked data if it's usable\n", " if is_usable:\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " unbiased_linked_data.to_csv(out_data_file)\n", " print(f\"Saved processed linked data to {out_data_file}\")\n", " else:\n", " print(\"Dataset validation failed. Final linked data not saved.\")\n", " \n", "except Exception as e:\n", " print(f\"Error in processing clinical data: {e}\")\n", " # If we failed to extract clinical data, update the 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=True,\n", " is_trait_available=False,\n", " is_biased=None,\n", " df=pd.DataFrame(),\n", " note=\"Failed to extract clinical data. Gene expression data is available but missing trait information.\"\n", " )\n", " print(\"Dataset validation failed due to missing clinical data. Only gene data 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 }