{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "bcedc742", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:08:29.135514Z", "iopub.status.busy": "2025-03-25T08:08:29.135411Z", "iopub.status.idle": "2025-03-25T08:08:29.292861Z", "shell.execute_reply": "2025-03-25T08:08:29.292543Z" } }, "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 = \"GSE61225\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Metabolic_Rate\"\n", "in_cohort_dir = \"../../input/GEO/Metabolic_Rate/GSE61225\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Metabolic_Rate/GSE61225.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Metabolic_Rate/gene_data/GSE61225.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Metabolic_Rate/clinical_data/GSE61225.csv\"\n", "json_path = \"../../output/preprocess/Metabolic_Rate/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "babe19b2", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "de738f4f", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:08:29.294199Z", "iopub.status.busy": "2025-03-25T08:08:29.294062Z", "iopub.status.idle": "2025-03-25T08:08:29.433262Z", "shell.execute_reply": "2025-03-25T08:08:29.432927Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Files in the directory:\n", "['GSE61225_family.soft.gz', 'GSE61225_series_matrix.txt.gz']\n", "SOFT file: ../../input/GEO/Metabolic_Rate/GSE61225/GSE61225_family.soft.gz\n", "Matrix file: ../../input/GEO/Metabolic_Rate/GSE61225/GSE61225_series_matrix.txt.gz\n", "Background Information:\n", "!Series_title\t\"Gene expression changes in blood RNA after swimming in a pool\"\n", "!Series_summary\t\"Trihalomethanes (THM) are a class of disinfection by-products in chlorinated waters linked to deleterious health effects in humans although biological mechanisms are unclear. We aimed to study short-term changes in blood gene expression of adult recreational swimmers associated with physical activity and THM exposure.\"\n", "!Series_summary\t\"Adult volunteers (18-50 years, non-smokers, non-asthmatics) swam 40 minutes in an indoor chlorinated pool in Barcelona. Blood samples and THM measurements in exhaled breath were collected before and 5 min/1h after swimming, respectively. Physical activity intensity was calculated as metabolic equivalents (METs). Gene expression in whole blood RNA was evaluated using Illumina HumanHT-12v3 Expression-BeadChip. Linear mixed models, Gene Set Enrichment Analyses-GSEA and mediation analyses were used.\"\n", "!Series_summary\t\"The study population comprised 37 before-after pairs, with mean age 31 years (SD: 6.0), 60% female, and average changes before-after swimming of 1.75 METs (SD: 1.36) and 0.23 µg/m3 of exhaled bromoform (SD: 0.23). Among THM, bromoform yielded the strongest effect on gene expression changes. Eighty eight probes were associated with bromoform, 326 probes with MET and 77 probes overlapped. In mutually adjusted models, 15 probes remained significant for MET after False Discovery Rate (FDR). Although not FDR significant, in 23 nominally significant probes (p-value <0.05), fulfilling criteria for exploring mediation, 29.5 to 53.4% of MET effect was mediated by exhaled bromoform. Individual genes in this subset and the GSEA of the mutually adjusted gene lists of bromoform and MET were associated with pathways related to inflammatory/immune response and to several cancers.\"\n", "!Series_summary\t\"In this first study evaluating short-term gene expression changes associated with swimming in a chlorinated pool, changes in gene expression were observed in association with physical activity with part of this effect mediated through bromoform exposure. Identified genes were correlated with inflammatory, immune response and cancer pathways. These results need replication in larger studies.\"\n", "!Series_overall_design\t\"Expression profile differences were determined between total RNA extracted before and after exposure to trihalomethanes present in swimming pool water for 40 minute from whole blood samples from 33 healthy human individuals.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['subject: 1', 'subject: 2', 'subject: 10', 'subject: 32', 'subject: 48', 'subject: 16', 'subject: 49', 'subject: 57', 'subject: 3', 'subject: 4', 'subject: 5', 'subject: 6', 'subject: 7', 'subject: 17', 'subject: 22', 'subject: 23', 'subject: 24', 'subject: 26', 'subject: 27', 'subject: 29', 'subject: 30', 'subject: 37', 'subject: 38', 'subject: 39', 'subject: 40', 'subject: 41', 'subject: 42', 'subject: 43', 'subject: 44', 'subject: 45'], 1: ['experimental repetition for same subject: 1', 'experimental repetition for same subject: 2'], 2: ['swimming pool water exposure time: 0 minutes', 'swimming pool water exposure time: 40 minutes'], 3: ['exhaled bromoform: 0.0930239', 'exhaled bromoform: 0.1312782', 'exhaled bromoform: 0.1290846', 'exhaled bromoform: 0.3099453', 'exhaled bromoform: 0.1330082', 'exhaled bromoform: 0.181454', 'exhaled bromoform: 0.2909702', 'exhaled bromoform: 0.2331693', 'exhaled bromoform: 0.126657', 'exhaled bromoform: 0.1524894', 'exhaled bromoform: 0.1347233', 'exhaled bromoform: 0.1412609', 'exhaled bromoform: 0.1832405', 'exhaled bromoform: 0.1198945', 'exhaled bromoform: 0.1475746', 'exhaled bromoform: 0.1465823', 'exhaled bromoform: 0.5277591', 'exhaled bromoform: 0.6841336', 'exhaled bromoform: 0.4507793', 'exhaled bromoform: 0.5180801', 'exhaled bromoform: 0.4502333', 'exhaled bromoform: 0.5977831', 'exhaled bromoform: 0.4006408', 'exhaled bromoform: 0.4996128', 'exhaled bromoform: 0.2518291', 'exhaled bromoform: 0.15765', 'exhaled bromoform: 0.4291167', 'exhaled bromoform: 0.3315417', 'exhaled bromoform: 0.4480595', 'exhaled bromoform: 0.4557298'], 4: ['metabolic equivalents: 0.681873816522757', 'metabolic equivalents: 0.8523423', 'metabolic equivalents: 0.665104620956877', 'metabolic equivalents: 0.8313807', 'metabolic equivalents: 0.786010716020953', 'metabolic equivalents: 0.9825132', 'metabolic equivalents: 0.744848045678339', 'metabolic equivalents: 0.9310601', 'metabolic equivalents: 0.814710221540659', 'metabolic equivalents: 1.018388', 'metabolic equivalents: 0.709058218744461', 'metabolic equivalents: 0.8863227', 'metabolic equivalents: 0.733268847575824', 'metabolic equivalents: 0.9165859', 'metabolic equivalents: 0.728783827412329', 'metabolic equivalents: 0.9109797', 'metabolic equivalents: 0.759969166965226', 'metabolic equivalents: 2.277797', 'metabolic equivalents: 0.863847192835992', 'metabolic equivalents: 2.987472', 'metabolic equivalents: 0.732301833893021', 'metabolic equivalents: 4.727416', 'metabolic equivalents: 0.755339902416559', 'metabolic equivalents: 3.308808', 'metabolic equivalents: 0.757193473208602', 'metabolic equivalents: 0.9464918', 'metabolic equivalents: 1.471296', 'metabolic equivalents: 0.812838481910338', 'metabolic equivalents: 3.748088', 'metabolic equivalents: 0.915727555354096'], 5: ['gender: female', 'gender: male'], 6: ['age: 31.60849', 'age: 24.39425', 'age: 51.2115', 'age: 30.16838', 'age: 26.02053', 'age: 29.64819', 'age: 33.63176', 'age: 28.3258', 'age: 27.32101', 'age: 26.20945', 'age: 30.19576', 'age: 35.37851', 'age: 23.36208', 'age: 38.17112', 'age: 41.41821', 'age: 40.75838', 'age: 22.71869', 'age: 37.81246', 'age: 30.9076', 'age: 29.45654', 'age: 33.64271', 'age: 30.43669', 'age: 32.33949', 'age: 24.53114', 'age: 30.20671', 'age: 39.97262', 'age: 39.2334', 'age: 25.21013', 'age: 25.42916', 'age: 28.46544']}\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": "8d38f879", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "349f651a", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "id": "f593aec7", "metadata": {}, "source": [ "### Step 3: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "9ea52d87", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:08:29.434530Z", "iopub.status.busy": "2025-03-25T08:08:29.434422Z", "iopub.status.idle": "2025-03-25T08:08:29.442241Z", "shell.execute_reply": "2025-03-25T08:08:29.441903Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Files in ../../input/GEO/Metabolic_Rate/GSE61225:\n", "['GSE61225_family.soft.gz', 'GSE61225_series_matrix.txt.gz']\n", "Clinical data file not found.\n", "Background information file not found.\n", "\n", "Gene expression data exists: False\n", "No trait data available, skipping clinical feature extraction.\n" ] } ], "source": [ "# Let's first examine the input data to determine what's available\n", "import os\n", "import pandas as pd\n", "import numpy as np\n", "import json\n", "from typing import Optional, Callable, Dict, Any\n", "\n", "# Let's check what files are available in the cohort directory\n", "print(f\"Files in {in_cohort_dir}:\")\n", "print(os.listdir(in_cohort_dir))\n", "\n", "# Load and examine the clinical data\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", " print(\"\\nClinical data shape:\", clinical_data.shape)\n", " print(\"\\nClinical data unique values:\")\n", " for i, row in clinical_data.iterrows():\n", " unique_values = pd.Series(row.astype(str).unique())\n", " print(f\"Row {i}: {unique_values.tolist()}\")\n", "else:\n", " print(\"Clinical data file not found.\")\n", "\n", "# Load and examine the background information\n", "background_path = os.path.join(in_cohort_dir, \"background.txt\")\n", "if os.path.exists(background_path):\n", " with open(background_path, 'r') as file:\n", " background_info = file.read()\n", " print(\"\\nBackground information:\")\n", " print(background_info)\n", "else:\n", " print(\"Background information file not found.\")\n", "\n", "# Check if gene expression data is available\n", "expression_path = os.path.join(in_cohort_dir, \"expression_data.csv\")\n", "gene_file_exists = os.path.exists(expression_path)\n", "print(f\"\\nGene expression data exists: {gene_file_exists}\")\n", "\n", "if gene_file_exists:\n", " # Peek at the expression data to ensure it's gene expression and not miRNA/methylation\n", " expr_data = pd.read_csv(expression_path, nrows=5)\n", " print(\"\\nExpression data preview (first 5 rows):\")\n", " print(expr_data.head())\n", "\n", "# Based on the data examination, determine availability and conversion functions\n", "\n", "# 1. Gene Expression Data Availability\n", "# If gene expression data exists and appears to be gene expression (not miRNA or methylation)\n", "is_gene_available = gene_file_exists # We'll assume it's gene expression if the file exists\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "\n", "# For Metabolic Rate (trait)\n", "# Let's initialize to None and update based on data examination\n", "trait_row = None\n", "age_row = None\n", "gender_row = None\n", "\n", "# Function to convert trait values\n", "def convert_trait(value):\n", " if pd.isna(value) or value == \"nan\":\n", " return None\n", " \n", " # Extract the value after the colon if present\n", " if \":\" in str(value):\n", " value = str(value).split(\":\", 1)[1].strip()\n", " \n", " # Convert to float, handle expected formats\n", " try:\n", " return float(value)\n", " except (ValueError, TypeError):\n", " return None\n", "\n", "# Function to convert age values\n", "def convert_age(value):\n", " if pd.isna(value) or value == \"nan\":\n", " return None\n", " \n", " # Extract the value after the colon if present\n", " if \":\" in str(value):\n", " value = str(value).split(\":\", 1)[1].strip()\n", " \n", " # Try to extract age as a number\n", " try:\n", " # Look for numbers in the string\n", " import re\n", " numbers = re.findall(r'\\d+', str(value))\n", " if numbers:\n", " return float(numbers[0])\n", " return None\n", " except (ValueError, TypeError):\n", " return None\n", "\n", "# Function to convert gender values\n", "def convert_gender(value):\n", " if pd.isna(value) or value == \"nan\":\n", " return None\n", " \n", " # Extract the value after the colon if present\n", " if \":\" in str(value):\n", " value = str(value).split(\":\", 1)[1].strip().lower()\n", " else:\n", " value = str(value).lower()\n", " \n", " # Convert to binary (0 for female, 1 for male)\n", " if 'female' in value or 'f' == value:\n", " return 0\n", " elif 'male' in value or 'm' == value:\n", " return 1\n", " return None\n", "\n", "# Based on clinical_data examination, we need to assign appropriate row indices\n", "# For this example, I'll use placeholder values that will be updated after seeing the data\n", "trait_row = None # Will be updated based on data inspection\n", "age_row = None # Will be updated based on data inspection\n", "gender_row = None # Will be updated based on data inspection\n", "\n", "# After examining the clinical data output above, we can determine which rows contain our variables of interest\n", "# For now, we're setting them to None, but we'll update based on the inspection of the data\n", "\n", "# Assuming trait_row is determined, check if trait data is available\n", "is_trait_available = trait_row is not None\n", "\n", "# 3. Save Metadata\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", " selected_clinical = 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 selected clinical features\n", " print(\"\\nSelected clinical features preview:\")\n", " print(preview_df(selected_clinical))\n", " \n", " # Save the clinical data\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " selected_clinical.to_csv(out_clinical_data_file, index=False)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n", "else:\n", " print(\"No trait data available, skipping clinical feature extraction.\")\n" ] }, { "cell_type": "markdown", "id": "6884fec8", "metadata": {}, "source": [ "### Step 4: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "0958b238", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:08:29.443339Z", "iopub.status.busy": "2025-03-25T08:08:29.443229Z", "iopub.status.idle": "2025-03-25T08:08:29.661970Z", "shell.execute_reply": "2025-03-25T08:08:29.661618Z" } }, "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: 26023\n", "First 20 gene/probe identifiers:\n", "Index(['ILMN_1343295', 'ILMN_1651209', 'ILMN_1651228', 'ILMN_1651229',\n", " 'ILMN_1651230', 'ILMN_1651232', 'ILMN_1651238', 'ILMN_1651254',\n", " 'ILMN_1651259', 'ILMN_1651260', 'ILMN_1651262', 'ILMN_1651268',\n", " 'ILMN_1651278', 'ILMN_1651281', 'ILMN_1651282', 'ILMN_1651285',\n", " 'ILMN_1651286', 'ILMN_1651303', 'ILMN_1651310', 'ILMN_1651315'],\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": "89f289fa", "metadata": {}, "source": [ "### Step 5: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "09b8b6e2", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:08:29.663174Z", "iopub.status.busy": "2025-03-25T08:08:29.663055Z", "iopub.status.idle": "2025-03-25T08:08:29.665060Z", "shell.execute_reply": "2025-03-25T08:08:29.664753Z" } }, "outputs": [], "source": [ "# These identifiers with the prefix \"ILMN_\" are Illumina probe IDs, not human gene symbols.\n", "# They need to be mapped to standard human gene symbols for analysis.\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "252e4d32", "metadata": {}, "source": [ "### Step 6: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "8bebb960", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:08:29.666082Z", "iopub.status.busy": "2025-03-25T08:08:29.665970Z", "iopub.status.idle": "2025-03-25T08:08:32.830888Z", "shell.execute_reply": "2025-03-25T08:08:32.830289Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene annotation preview:\n", "{'ID': ['ILMN_1343295', 'ILMN_1651209', 'ILMN_1651228', 'ILMN_1651229', 'ILMN_1651230'], 'Array_Address_Id': ['4490161', '2940221', '650349', '2510494', '2940041'], 'ILMN_Gene': ['GAPDH', 'SLC35E2', 'RPS28', 'IPO13', 'TESSP1'], 'ILMN_Synonyms': ['G3PD; GAPD; MGC88685', 'MGC117254; MGC138494; DKFZp686M0869; FLJ34996; FLJ44537; MGC126715; MGC104754; KIAA0447', nan, 'RANBP13; KIAA0724; IMP13; KAP13', nan], 'ILMN_CHR': ['12', '1', '19', '1', nan], 'ILMN_Probe_Chr_Orientation': ['+', '-', '+', '+', nan], 'SEQUENCE': ['CTTCAACAGCGACACCCACTCCTCCACCTTTGACGCTGGGGCTGGCATTG', 'TCACGGCGTACGCCCTCATGGGGAAAATCTCCCCGGTGACTTTCAGGTCC', 'CGCCACACGTAACTGAGATGCTCCTTTAAATAAAGCGTTTGTGTTTCAAG', 'ACAAGAGGCGGGTGAAGGAGATGGTGAAGGAGTTCACACTGCTGTGCCGG', 'GTGATGTCCCACAGTACACCCAGGCCAAACCCCTCCCAGCTGTTGCTGCT'], 'QCStatus_UCSC': ['OK: single match RefSeq', 'OK: single match mRNA', 'OK: single match mRNA', 'OK: single match RefSeq', 'OK: single match mRNA'], 'UCSC_CountMatches': [10.0, 1.0, 1.0, 2.0, 1.0], 'UCSC_GENES': ['GAPDH', 'SLC35E2', 'RPS28', 'IPO13', 'PRSS41'], 'UCSC_CHROMOSOME': ['CHR12', 'CHR1', 'CHR19', 'CHR1', 'CHR16'], 'UCSC_MatchedPositions': ['6643656-6647536, 6643699-6647536, 6643957-6647536, 6646452-6647536, 6645828-6647536, 6644467-6647536', '1663680-1677431', '8386383-8387278', '44412477-44433693, 44431610-44433693', '2848485-2855132'], 'UCSC_MatchedMrna': ['uc001qor.1, uc009zep.1, uc001qos.1, uc001qou.1, uc001qox.1, uc001qow.1, uc001qot.1, uc001qov.1, uc001qop.1, uc001qoq.1', 'uc001aib.1', 'uc002mjn.2', 'uc001ckx.2, uc001cky.2', 'uc010uwi.1'], 'IPA_GENES_120823': ['GAPDH', 'SLC35E2', 'RPS28', 'IPO13', 'PRSS41'], 'QC_COMMENT': ['good', 'good', 'good', 'good', 'good'], 'ChrUnique': ['CHR12', 'CHR1', 'CHR19', 'CHR1', 'CHR16'], 'MatchedPosStart': [6643656.0, 1663680.0, 8386383.0, 44412477.0, 2848485.0], 'MatchedPosEnd': [6647536.0, 1677431.0, 8387278.0, 44433693.0, 2855132.0], 'MatchedMidPos': [6645596.0, 1670555.5, 8386830.5, 44423085.0, 2851808.5], 'Chr': ['12', '1', '19', '1', '16'], 'Cytoband': ['12p13', '1p36.33', '19p13.2', '1p34.1', '16p13.3'], 'REFSEQ': ['c(\\\\NM_001256799\\\\, \\\\NM_002046\\\\, \\\\NP_001243728\\\\, \\\\NP_002037\\\\, \\\\XM_005253678\\\\, \\\\XP_005253735\\\\)', 'c(\\\\NM_001199787\\\\, \\\\NM_182838\\\\, \\\\NP_001186716\\\\, \\\\NP_878258\\\\, \\\\XM_005244816\\\\, \\\\XM_005244817\\\\, \\\\XP_005244873\\\\, \\\\XP_005244874\\\\, \\\\XR_241047\\\\)', 'c(\\\\NM_001031\\\\, \\\\NP_001022\\\\)', 'c(\\\\NM_014652\\\\, \\\\NP_055467\\\\, \\\\XM_003846624\\\\, \\\\XP_003846672\\\\)', 'c(\\\\NM_001135086\\\\, \\\\NP_001128558\\\\)'], 'EntrezID': [2597.0, 9906.0, 6234.0, 9670.0, 360226.0], 'ORF': ['GAPDH', 'SLC35E2', 'RPS28', 'IPO13', 'PRSS41'], 'Name': ['glyceraldehyde-3-phosphate dehydrogenase', 'solute carrier family 35, member E2', 'ribosomal protein S28', 'importin 13', 'protease, serine, 41']}\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": "ae50fc67", "metadata": {}, "source": [ "### Step 7: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "b5b0dcc2", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:08:32.832822Z", "iopub.status.busy": "2025-03-25T08:08:32.832687Z", "iopub.status.idle": "2025-03-25T08:08:33.098276Z", "shell.execute_reply": "2025-03-25T08:08:33.097722Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene mapping preview (first 5 rows):\n", "{'ID': ['ILMN_1343295', 'ILMN_1651209', 'ILMN_1651228', 'ILMN_1651229', 'ILMN_1651230'], 'Gene': ['GAPDH', 'SLC35E2', 'RPS28', 'IPO13', 'TESSP1']}\n", "\n", "Gene expression data after mapping:\n", "Number of genes: 17047\n", "First 10 genes:\n", "Index(['A1CF', 'A26A1', 'A26B1', 'A26C3', 'A2BP1', 'A2M', 'A3GALT2', 'A4GALT',\n", " 'A4GNT', 'AAA1'],\n", " dtype='object', name='Gene')\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene expression data after normalization:\n", "Number of genes after normalization: 16582\n", "First 10 normalized genes:\n", "Index(['A1CF', 'A2M', 'A3GALT2', 'A4GALT', 'A4GNT', 'AAA1', 'AAAS', 'AACS',\n", " 'AADAC', 'AADACL2'],\n", " dtype='object', name='Gene')\n" ] } ], "source": [ "# 1. Identify the appropriate columns for gene mapping\n", "# Looking at the previous output:\n", "# - 'ID' column contains Illumina probe IDs (e.g., 'ILMN_1343295')\n", "# - Several columns contain gene symbols, but 'ILMN_Gene' appears to be the primary one with gene symbols\n", "probe_id_column = 'ID' # Column with probe identifiers\n", "gene_symbol_column = 'ILMN_Gene' # Column with gene symbols\n", "\n", "# 2. Extract mapping between gene identifiers and gene symbols\n", "gene_mapping = get_gene_mapping(gene_annotation, probe_id_column, gene_symbol_column)\n", "print(\"\\nGene mapping preview (first 5 rows):\")\n", "print(preview_df(gene_mapping))\n", "\n", "# 3. Apply the gene mapping to convert probe-level measurements to gene-level expression\n", "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n", "print(\"\\nGene expression data after mapping:\")\n", "print(\"Number of genes:\", len(gene_data))\n", "print(\"First 10 genes:\")\n", "print(gene_data.index[:10])\n", "\n", "# 4. Additional step: normalize gene symbols for consistency \n", "gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(\"\\nGene expression data after normalization:\")\n", "print(\"Number of genes after normalization:\", len(gene_data))\n", "print(\"First 10 normalized genes:\")\n", "print(gene_data.index[:10])\n" ] }, { "cell_type": "markdown", "id": "4810a8e0", "metadata": {}, "source": [ "### Step 8: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "72c94e91", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:08:33.100098Z", "iopub.status.busy": "2025-03-25T08:08:33.099972Z", "iopub.status.idle": "2025-03-25T08:08:42.116023Z", "shell.execute_reply": "2025-03-25T08:08:42.115370Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Shape of gene data after normalization: (16582, 74)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Saved normalized gene data to ../../output/preprocess/Metabolic_Rate/gene_data/GSE61225.csv\n", "Clinical data preview:\n", "{'Metabolic_Rate': [0.681873816522757, 0.8523423, 0.665104620956877, 0.8313807, 0.786010716020953], 'Age': [31.60849, 31.60849, 24.39425, 24.39425, 51.2115], 'Gender': [0.0, 0.0, 0.0, 0.0, 1.0]}\n", "Saved clinical data to ../../output/preprocess/Metabolic_Rate/clinical_data/GSE61225.csv\n", "Shape of linked data: (74, 16585)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Shape of linked data after handling missing values: (74, 16585)\n", "Quartiles for 'Metabolic_Rate':\n", " 25%: 0.7391046411728177\n", " 50% (Median): 0.883957846599822\n", " 75%: 2.267302\n", "Min: 0.595372813525237\n", "Max: 5.917071\n", "The distribution of the feature 'Metabolic_Rate' in this dataset is fine.\n", "\n", "Quartiles for 'Age':\n", " 25%: 27.32101\n", " 50% (Median): 30.16838\n", " 75%: 33.63176\n", "Min: 22.71869\n", "Max: 51.2115\n", "The distribution of the feature 'Age' in this dataset is fine.\n", "\n", "For the feature 'Gender', the least common label is '1.0' with 30 occurrences. This represents 40.54% of the dataset.\n", "The distribution of the feature 'Gender' in this dataset is fine.\n", "\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Saved processed linked data to ../../output/preprocess/Metabolic_Rate/GSE61225.csv\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. Create clinical data from the sample characteristics dictionary\n", "# Extract metabolic rate (the actual trait), gender, and age from the clinical data\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", "characteristics_dict = get_unique_values_by_row(clinical_data)\n", "\n", "# Define conversion functions for the clinical features\n", "def convert_metabolic_rate(value):\n", " if pd.isna(value) or value == \"nan\":\n", " return None\n", " # Extract numeric value after the colon\n", " if \":\" in str(value):\n", " value = str(value).split(\":\", 1)[1].strip()\n", " try:\n", " return float(value)\n", " except (ValueError, TypeError):\n", " return None\n", "\n", "def convert_gender(value):\n", " if pd.isna(value) or value == \"nan\":\n", " return None\n", " if \":\" in str(value):\n", " value = str(value).split(\":\", 1)[1].strip().lower()\n", " else:\n", " value = str(value).lower()\n", " if 'female' in value:\n", " return 0\n", " elif 'male' in value:\n", " return 1\n", " return None\n", "\n", "def convert_age(value):\n", " if pd.isna(value) or value == \"nan\":\n", " return None\n", " if \":\" in str(value):\n", " value = str(value).split(\":\", 1)[1].strip()\n", " try:\n", " return float(value)\n", " except (ValueError, TypeError):\n", " return None\n", "\n", "# Create the clinical dataframe with the trait and demographic features\n", "clinical_df = geo_select_clinical_features(\n", " clinical_data,\n", " trait=\"Metabolic_Rate\",\n", " trait_row=4, # Row 4 contains metabolic equivalents\n", " convert_trait=convert_metabolic_rate,\n", " gender_row=5, # Row 5 contains gender information\n", " convert_gender=convert_gender,\n", " age_row=6, # Row 6 contains age information\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.T.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 subjects before and after swimming in a chlorinated pool, with metabolic rate measurements.\"\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.\")" ] } ], "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 }