{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "de0970bc", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:58:53.822561Z", "iopub.status.busy": "2025-03-25T05:58:53.822340Z", "iopub.status.idle": "2025-03-25T05:58:53.990514Z", "shell.execute_reply": "2025-03-25T05:58:53.990110Z" } }, "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 = \"Osteoarthritis\"\n", "cohort = \"GSE107105\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Osteoarthritis\"\n", "in_cohort_dir = \"../../input/GEO/Osteoarthritis/GSE107105\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Osteoarthritis/GSE107105.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Osteoarthritis/gene_data/GSE107105.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Osteoarthritis/clinical_data/GSE107105.csv\"\n", "json_path = \"../../output/preprocess/Osteoarthritis/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "e494f8c6", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "8b88e01a", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:58:53.991711Z", "iopub.status.busy": "2025-03-25T05:58:53.991567Z", "iopub.status.idle": "2025-03-25T05:58:54.152222Z", "shell.execute_reply": "2025-03-25T05:58:54.151708Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Microarray analysis of freshly isolated synovial fibroblast subsets in patients with rheumatoid arthritis or osteoarthritis\"\n", "!Series_summary\t\"Transcriptomics of distinct subpopulations of synovial fibroblasts from osteoarthritis and rheumatoid arthritis arthroplasty tissues.\"\n", "!Series_overall_design\t\"We gated 7 subsets of synovial fibroblasts by protein surface markers and used microarrays to profile gene expression of cells taken from each gate. This data includes 37 samples from 3 osteoarthritis donors and 3 rheumatoid arthritis donors.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['disease: OA', 'disease: RA'], 1: ['age: 59', 'age: 78', 'age: 86', 'age: 51', 'age: 79', 'age: 48'], 2: ['Sex: Female', 'Sex: Male'], 3: ['joint: Knee', 'joint: MP'], 4: ['surgery_date: 2014-04-25', 'surgery_date: 2014-07-18', 'surgery_date: 2014-09-26', 'surgery_date: 2014-04-08', 'surgery_date: 2014-06-12', 'surgery_date: 2014-10-20'], 5: ['microarray_date: 2014-06-19', 'microarray_date: 2014-12-01', 'microarray_date: 2014-08-04', 'microarray_date: 2014-12-18'], 6: ['cd34_protein: -', 'cd34_protein: +', 'cd34_protein: NA'], 7: ['thy1_protein: -', 'thy1_protein: +', 'thy1_protein: NA'], 8: ['cdh11_protein: +', 'cdh11_protein: -', 'cdh11_protein: NA'], 9: ['cd146_protein: NA', 'cd146_protein: +'], 10: ['donor_percent_cd146h: NA', 'donor_percent_cd146h: 0.0049'], 11: ['donor_percent_cd34l_thy1l_cdh11h: 0.589', 'donor_percent_cd34l_thy1l_cdh11h: 0.405', 'donor_percent_cd34l_thy1l_cdh11h: 0.629', 'donor_percent_cd34l_thy1l_cdh11h: 0.023', 'donor_percent_cd34l_thy1l_cdh11h: 0.626', 'donor_percent_cd34l_thy1l_cdh11h: 0.391'], 12: ['donor_percent_cd34l_thy1h_cdh11h: 0.041', 'donor_percent_cd34l_thy1h_cdh11h: 0.0808', 'donor_percent_cd34l_thy1h_cdh11h: 0.122', 'donor_percent_cd34l_thy1h_cdh11h: 0.852', 'donor_percent_cd34l_thy1h_cdh11h: 0.0696', 'donor_percent_cd34l_thy1h_cdh11h: 0.269'], 13: ['donor_percent_cd34l_thy1h_cdh11l: NA', 'donor_percent_cd34l_thy1h_cdh11l: 0.0176', 'donor_percent_cd34l_thy1h_cdh11l: 0.0063', 'donor_percent_cd34l_thy1h_cdh11l: 0.0616', 'donor_percent_cd34l_thy1h_cdh11l: 0.0123'], 14: ['donor_percent_cd34l_thy1l_cdh11l: 0.216', 'donor_percent_cd34l_thy1l_cdh11l: 0.367', 'donor_percent_cd34l_thy1l_cdh11l: 0.151', 'donor_percent_cd34l_thy1l_cdh11l: 0.0797', 'donor_percent_cd34l_thy1l_cdh11l: 0.187', 'donor_percent_cd34l_thy1l_cdh11l: 0.133'], 15: ['donor_percent_cd34h_thy1l_cdh11h: 0.134', 'donor_percent_cd34h_thy1l_cdh11h: 0.251', 'donor_percent_cd34h_thy1l_cdh11h: 0.165', 'donor_percent_cd34h_thy1l_cdh11h: 0.0105', 'donor_percent_cd34h_thy1l_cdh11h: 0.199', 'donor_percent_cd34h_thy1l_cdh11h: 0.0095'], 16: ['donor_percent_cd34h_thy1h_cdh11h: 0.728', 'donor_percent_cd34h_thy1h_cdh11h: 0.6', 'donor_percent_cd34h_thy1h_cdh11h: 0.719', 'donor_percent_cd34h_thy1h_cdh11h: 0.882', 'donor_percent_cd34h_thy1h_cdh11h: 0.627', 'donor_percent_cd34h_thy1h_cdh11h: 0.929'], 17: ['donor_percent_cd34h_thy1h_cdh11l: NA', 'donor_percent_cd34h_thy1h_cdh11l: 0.0374', 'donor_percent_cd34h_thy1h_cdh11l: 0.0177', 'donor_percent_cd34h_thy1h_cdh11l: 0.0391', 'donor_percent_cd34h_thy1h_cdh11l: 0.0253', 'donor_percent_cd34h_thy1h_cdh11l: 0.0175'], 18: ['donor_percent_cd34h_thy1l_cdh11l: NA', 'donor_percent_cd34h_thy1l_cdh11l: 0.0459', 'donor_percent_cd34h_thy1l_cdh11l: 0.0154', 'donor_percent_cd34h_thy1l_cdh11l: 0.0033', 'donor_percent_cd34h_thy1l_cdh11l: 0.0188', 'donor_percent_cd34h_thy1l_cdh11l: 0.0011']}\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": "b973cf21", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "d2b9108a", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:58:54.154061Z", "iopub.status.busy": "2025-03-25T05:58:54.153918Z", "iopub.status.idle": "2025-03-25T05:58:54.160210Z", "shell.execute_reply": "2025-03-25T05:58:54.159749Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Initial evaluation complete for cohort: GSE107105\n", "- Gene expression data available: True\n", "- Trait data available: True\n", "- trait_row: 0\n", "- age_row: 1\n", "- gender_row: 2\n" ] } ], "source": [ "import os\n", "import re\n", "import pandas as pd\n", "import numpy as np\n", "import json\n", "from typing import Dict, Any, List, Callable, Optional, Union, Tuple\n", "\n", "# 1. Gene Expression Data Availability\n", "# Based on the series title and summary, this dataset appears to contain microarray data\n", "# which is a form of gene expression data, not just miRNA or methylation data\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "\n", "# For trait (Osteoarthritis), we can see \"disease: OA\" and \"disease: RA\" in row 0\n", "# where OA = Osteoarthritis and RA = Rheumatoid Arthritis\n", "trait_row = 0\n", "\n", "# For age, we can see values like \"age: 59\", \"age: 78\", etc. in row 1\n", "age_row = 1\n", "\n", "# For gender, we can see \"Sex: Female\" and \"Sex: Male\" in row 2\n", "gender_row = 2\n", "\n", "# 2.2 Data Type Conversion\n", "\n", "def convert_trait(value: str) -> Optional[int]:\n", " \"\"\"\n", " Convert trait value to binary (0 for non-Osteoarthritis, 1 for Osteoarthritis)\n", " \"\"\"\n", " if not isinstance(value, str):\n", " return None\n", " \n", " # Extract the value after the colon\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " # Convert to binary\n", " if value.upper() == \"OA\" or \"OSTEOARTHRITIS\" in value.upper():\n", " return 1\n", " elif value.upper() == \"RA\" or \"RHEUMATOID\" in value.upper():\n", " return 0\n", " else:\n", " return None\n", "\n", "def convert_age(value: str) -> Optional[float]:\n", " \"\"\"\n", " Convert age value to continuous numeric value\n", " \"\"\"\n", " if not isinstance(value, str):\n", " return None\n", " \n", " # Extract the value after the colon\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " # Try to convert to float\n", " try:\n", " return float(value)\n", " except ValueError:\n", " return None\n", "\n", "def convert_gender(value: str) -> Optional[int]:\n", " \"\"\"\n", " Convert gender value to binary (0 for female, 1 for male)\n", " \"\"\"\n", " if not isinstance(value, str):\n", " return None\n", " \n", " # Extract the value after the colon\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " # Convert to binary\n", " if value.upper() in [\"FEMALE\", \"F\"]:\n", " return 0\n", " elif value.upper() in [\"MALE\", \"M\"]:\n", " return 1\n", " else:\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Based on trait_row being not None, trait data is available\n", "is_trait_available = trait_row is not None\n", "\n", "# Initial filtering on dataset usability\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", "# Skip this section as we don't have access to the clinical_data yet\n", "# We'll need to wait for the next steps where the data is fully loaded\n", "# This information will be available in subsequent processing steps\n", "\n", "print(f\"Initial evaluation complete for cohort: {cohort}\")\n", "print(f\"- Gene expression data available: {is_gene_available}\")\n", "print(f\"- Trait data available: {is_trait_available}\")\n", "print(f\"- trait_row: {trait_row}\")\n", "print(f\"- age_row: {age_row}\")\n", "print(f\"- gender_row: {gender_row}\")\n" ] }, { "cell_type": "markdown", "id": "ea9aea1c", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "933472b4", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:58:54.161870Z", "iopub.status.busy": "2025-03-25T05:58:54.161735Z", "iopub.status.idle": "2025-03-25T05:58:54.379671Z", "shell.execute_reply": "2025-03-25T05:58:54.379137Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Matrix file found: ../../input/GEO/Osteoarthritis/GSE107105/GSE107105_series_matrix.txt.gz\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape: (53617, 36)\n", "First 20 gene/probe identifiers:\n", "Index(['16650001', '16650003', '16650005', '16650007', '16650009', '16650011',\n", " '16650013', '16650015', '16650017', '16650019', '16650021', '16650023',\n", " '16650025', '16650027', '16650029', '16650031', '16650033', '16650035',\n", " '16650037', '16650041'],\n", " dtype='object', name='ID')\n" ] } ], "source": [ "# 1. Get the SOFT and matrix file paths again \n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "print(f\"Matrix file found: {matrix_file}\")\n", "\n", "# 2. Use the get_genetic_data function from the library to get the gene_data\n", "try:\n", " gene_data = get_genetic_data(matrix_file)\n", " print(f\"Gene data shape: {gene_data.shape}\")\n", " \n", " # 3. Print the first 20 row IDs (gene or probe identifiers)\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" ] }, { "cell_type": "markdown", "id": "204e8081", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "d890b1be", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:58:54.381141Z", "iopub.status.busy": "2025-03-25T05:58:54.381019Z", "iopub.status.idle": "2025-03-25T05:58:54.383157Z", "shell.execute_reply": "2025-03-25T05:58:54.382783Z" } }, "outputs": [], "source": [ "# These gene identifiers appear to be probe IDs rather than human gene symbols\n", "# They are numerical identifiers (like '16650001') rather than standard gene symbols (like 'BRCA1', 'TP53', etc.)\n", "# These are likely platform-specific probe IDs that need to be mapped to gene symbols\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "3ec6741f", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "749f0e56", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:58:54.384507Z", "iopub.status.busy": "2025-03-25T05:58:54.384400Z", "iopub.status.idle": "2025-03-25T05:58:56.943189Z", "shell.execute_reply": "2025-03-25T05:58:56.942533Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene annotation preview:\n", "Columns in gene annotation: ['ID', 'RANGE_STRAND', 'RANGE_START', 'RANGE_END', 'total_probes', 'GB_ACC', 'SPOT_ID', 'RANGE_GB']\n", "{'ID': ['16657436', '16657440', '16657445', '16657447', '16657450'], 'RANGE_STRAND': ['+', '+', '+', '+', '+'], 'RANGE_START': [12190.0, 29554.0, 69091.0, 160446.0, 317811.0], 'RANGE_END': [13639.0, 31109.0, 70008.0, 161525.0, 328581.0], 'total_probes': [25.0, 28.0, 8.0, 13.0, 36.0], 'GB_ACC': ['NR_046018', nan, nan, nan, 'NR_024368'], 'SPOT_ID': ['chr1:12190-13639', 'chr1:29554-31109', 'chr1:69091-70008', 'chr1:160446-161525', 'chr1:317811-328581'], 'RANGE_GB': ['NC_000001.10', 'NC_000001.10', 'NC_000001.10', 'NC_000001.10', 'NC_000001.10']}\n", "\n", "Searching for platform information in SOFT file:\n", "!Series_platform_id = GPL16686\n", "\n", "Searching for gene symbol information in SOFT file:\n", "Found references to gene symbols:\n", "!Platform_relation = Alternative to: GPL25483 (Gene symbol version)\n", "\n", "Checking for additional annotation files in the directory:\n", "[]\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. Analyze the gene annotation dataframe to identify which columns contain the gene identifiers and gene symbols\n", "print(\"\\nGene annotation preview:\")\n", "print(f\"Columns in gene annotation: {gene_annotation.columns.tolist()}\")\n", "print(preview_df(gene_annotation, n=5))\n", "\n", "# Let's look for platform information in the SOFT file to understand the annotation better\n", "print(\"\\nSearching for platform information in SOFT file:\")\n", "with gzip.open(soft_file, 'rt') as f:\n", " for i, line in enumerate(f):\n", " if '!Series_platform_id' in line:\n", " print(line.strip())\n", " break\n", " if i > 100: # Limit search to first 100 lines\n", " print(\"Platform ID not found in first 100 lines\")\n", " break\n", "\n", "# Check if the SOFT file includes any reference to gene symbols\n", "print(\"\\nSearching for gene symbol information in SOFT file:\")\n", "with gzip.open(soft_file, 'rt') as f:\n", " gene_symbol_lines = []\n", " for i, line in enumerate(f):\n", " if 'GENE_SYMBOL' in line or 'gene_symbol' in line.lower() or 'symbol' in line.lower():\n", " gene_symbol_lines.append(line.strip())\n", " if i > 1000 and len(gene_symbol_lines) > 0: # Limit search but ensure we found something\n", " break\n", " \n", " if gene_symbol_lines:\n", " print(\"Found references to gene symbols:\")\n", " for line in gene_symbol_lines[:5]: # Show just first 5 matches\n", " print(line)\n", " else:\n", " print(\"No explicit gene symbol references found in first 1000 lines\")\n", "\n", "# Look for alternative annotation files or references in the directory\n", "print(\"\\nChecking for additional annotation files in the directory:\")\n", "all_files = os.listdir(in_cohort_dir)\n", "print([f for f in all_files if 'annotation' in f.lower() or 'platform' in f.lower() or 'gpl' in f.lower()])\n" ] }, { "cell_type": "markdown", "id": "ecdc6c86", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "5210e935", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:58:56.945114Z", "iopub.status.busy": "2025-03-25T05:58:56.944950Z", "iopub.status.idle": "2025-03-25T05:58:57.661553Z", "shell.execute_reply": "2025-03-25T05:58:57.661007Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Exploring additional annotation columns...\n", "Column 'ID': 1984229/1984229 non-null values (100.00%)\n", "Column 'RANGE_STRAND': 1982020/1984229 non-null values (99.89%)\n", "Column 'RANGE_START': 51772/1984229 non-null values (2.61%)\n", "Column 'RANGE_END': 51772/1984229 non-null values (2.61%)\n", "Column 'total_probes': 51772/1984229 non-null values (2.61%)\n", "Column 'GB_ACC': 17623/1984229 non-null values (0.89%)\n", "Column 'SPOT_ID': 53981/1984229 non-null values (2.72%)\n", "Column 'RANGE_GB': 47833/1984229 non-null values (2.41%)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "SPOT_ID examples: ['chr1:12190-13639', 'chr1:29554-31109', 'chr1:69091-70008', 'chr1:160446-161525', 'chr1:317811-328581', 'chr1:329790-342507', 'chr1:367640-368634', 'chr1:459656-461954', 'chr1:523009-532878', 'chr1:557143-566063']\n", "Sample GB_ACC values: ['NR_046018', 'NR_024368', 'NR_029406', 'XR_132471', 'NR_047526', 'NM_152486', 'NM_198317', 'NM_005101', 'NM_198576', 'NR_038869']\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene mapping shape: (17623, 2)\n", "Sample of gene mapping data:\n", " ID Gene\n", "0 16657436 NR_046018\n", "4 16657450 NR_024368\n", "7 16657476 NR_029406\n", "9 16657485 XR_132471\n", "15 16657514 NR_047526\n", "Total probes in expression data: 53617\n", "Probes with gene annotations: 17623 (32.87%)\n", "Extracted gene symbols from mapping: [[], [], [], [], [], [], [], [], [], []]\n", "Gene expression data shape after mapping: (16346, 36)\n", "First few gene symbols after mapping:\n", "['NM_000014', 'NM_000015', 'NM_000019', 'NM_000020', 'NM_000021', 'NM_000022', 'NM_000025', 'NM_000026', 'NM_000027', 'NM_000030']\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data saved to ../../output/preprocess/Osteoarthritis/gene_data/GSE107105.csv\n" ] } ], "source": [ "# 1. Analyze the gene identifiers in the gene expression data and gene annotation data\n", "# The platform ID is GPL16686, which appears to be a custom platform\n", "# We need to explore the annotation data more carefully to find usable gene identifiers\n", "\n", "# Let's look at more rows of the annotation to better understand the data structure\n", "print(\"Exploring additional annotation columns...\")\n", "\n", "# Check which columns might contain gene-related information\n", "for col in gene_annotation.columns:\n", " non_null_count = gene_annotation[col].notna().sum()\n", " total_count = len(gene_annotation)\n", " print(f\"Column '{col}': {non_null_count}/{total_count} non-null values ({non_null_count/total_count:.2%})\")\n", "\n", "# For this platform (GPL16686), we need to check if the SPOT_ID column contains genomic locations\n", "# that can be linked to gene identifiers\n", "spot_id_examples = gene_annotation['SPOT_ID'].dropna().head(10).tolist()\n", "print(f\"SPOT_ID examples: {spot_id_examples}\")\n", "\n", "# Let's check if we can extract any gene-related information from the annotation\n", "sample_gb_acc = gene_annotation['GB_ACC'].dropna().head(10).tolist()\n", "print(f\"Sample GB_ACC values: {sample_gb_acc}\")\n", "\n", "# Since the platform appears to be from a custom transcript-based approach, \n", "# we need to use both ID and GB_ACC columns\n", "prob_col = 'ID'\n", "gene_col = 'GB_ACC'\n", "\n", "# Create the mapping dataframe (for accession numbers)\n", "mapping_df = get_gene_mapping(gene_annotation, prob_col, gene_col)\n", "print(f\"Gene mapping shape: {mapping_df.shape}\")\n", "print(\"Sample of gene mapping data:\")\n", "print(mapping_df.head())\n", "\n", "# Check how many probes have gene annotations\n", "total_probes = len(gene_data.index)\n", "mapped_probes = len(mapping_df)\n", "print(f\"Total probes in expression data: {total_probes}\")\n", "print(f\"Probes with gene annotations: {mapped_probes} ({mapped_probes/total_probes:.2%})\")\n", "\n", "# Since the mapping data contains accession numbers instead of gene symbols,\n", "# let's modify the mapping before applying it\n", "# Let's first check if we have any gene symbols in the mapping\n", "sample_genes = mapping_df['Gene'].apply(extract_human_gene_symbols).head(10).tolist()\n", "print(f\"Extracted gene symbols from mapping: {sample_genes}\")\n", "\n", "# Since we're dealing with a custom array with limited gene annotations,\n", "# I'll augment the mapping process to keep the original accession numbers\n", "# This might not give us standard gene symbols, but it will preserve the data\n", "# for downstream analysis\n", "def custom_extract_identifiers(text):\n", " \"\"\"Extract gene identifiers including accession numbers like NR_/XR_ series\"\"\"\n", " if not isinstance(text, str):\n", " return []\n", " # Keep accession numbers intact\n", " return [text]\n", "\n", "# Create a modified version of the mapping dataframe that keeps accession numbers\n", "mapping_df_modified = mapping_df.copy()\n", "mapping_df_modified['Gene'] = mapping_df_modified['Gene'].apply(custom_extract_identifiers)\n", "\n", "# Apply gene mapping with the modified approach\n", "gene_data_with_acc = gene_data.copy()\n", "# Remove the index name to avoid conflicts during the join operation\n", "gene_data_with_acc.index.name = None\n", "\n", "# Perform a simpler mapping for this dataset\n", "# Convert expression matrix to have probe IDs as a column instead of index\n", "expression_df_reset = gene_data.reset_index()\n", "# Merge with mapping data\n", "merged_df = pd.merge(expression_df_reset, mapping_df, on='ID', how='inner')\n", "# Remove rows with missing gene information\n", "merged_df = merged_df.dropna(subset=['Gene'])\n", "# Extract sample columns (all columns except ID and Gene)\n", "sample_cols = [col for col in merged_df.columns if col not in ['ID', 'Gene']]\n", "# Group by Gene and calculate the mean expression for each gene\n", "gene_data = merged_df.groupby('Gene')[sample_cols].mean()\n", "\n", "print(f\"Gene expression data shape after mapping: {gene_data.shape}\")\n", "print(\"First few gene symbols after mapping:\")\n", "print(list(gene_data.index[:10]))\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\"Gene expression data saved to {out_gene_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "1c0e3774", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "d0bced55", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:58:57.663412Z", "iopub.status.busy": "2025-03-25T05:58:57.663265Z", "iopub.status.idle": "2025-03-25T05:59:04.594870Z", "shell.execute_reply": "2025-03-25T05:59:04.593814Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data shape: (16346, 36)\n", "Gene data column names (sample IDs):\n", "Index(['GSM2861345', 'GSM2861346', 'GSM2861347', 'GSM2861348', 'GSM2861349'], dtype='object')\n", "\n", "Raw clinical data structure:\n", "Clinical data shape: (19, 37)\n", "Clinical data columns: Index(['!Sample_geo_accession', 'GSM2861345', 'GSM2861346', 'GSM2861347',\n", " 'GSM2861348'],\n", " dtype='object')\n", "\n", "Sample characteristics dictionary:\n", "{0: ['disease: OA', 'disease: RA'], 1: ['age: 59', 'age: 78', 'age: 86', 'age: 51', 'age: 79', 'age: 48'], 2: ['Sex: Female', 'Sex: Male'], 3: ['joint: Knee', 'joint: MP'], 4: ['surgery_date: 2014-04-25', 'surgery_date: 2014-07-18', 'surgery_date: 2014-09-26', 'surgery_date: 2014-04-08', 'surgery_date: 2014-06-12', 'surgery_date: 2014-10-20'], 5: ['microarray_date: 2014-06-19', 'microarray_date: 2014-12-01', 'microarray_date: 2014-08-04', 'microarray_date: 2014-12-18'], 6: ['cd34_protein: -', 'cd34_protein: +', 'cd34_protein: NA'], 7: ['thy1_protein: -', 'thy1_protein: +', 'thy1_protein: NA'], 8: ['cdh11_protein: +', 'cdh11_protein: -', 'cdh11_protein: NA'], 9: ['cd146_protein: NA', 'cd146_protein: +'], 10: ['donor_percent_cd146h: NA', 'donor_percent_cd146h: 0.0049'], 11: ['donor_percent_cd34l_thy1l_cdh11h: 0.589', 'donor_percent_cd34l_thy1l_cdh11h: 0.405', 'donor_percent_cd34l_thy1l_cdh11h: 0.629', 'donor_percent_cd34l_thy1l_cdh11h: 0.023', 'donor_percent_cd34l_thy1l_cdh11h: 0.626', 'donor_percent_cd34l_thy1l_cdh11h: 0.391'], 12: ['donor_percent_cd34l_thy1h_cdh11h: 0.041', 'donor_percent_cd34l_thy1h_cdh11h: 0.0808', 'donor_percent_cd34l_thy1h_cdh11h: 0.122', 'donor_percent_cd34l_thy1h_cdh11h: 0.852', 'donor_percent_cd34l_thy1h_cdh11h: 0.0696', 'donor_percent_cd34l_thy1h_cdh11h: 0.269'], 13: ['donor_percent_cd34l_thy1h_cdh11l: NA', 'donor_percent_cd34l_thy1h_cdh11l: 0.0176', 'donor_percent_cd34l_thy1h_cdh11l: 0.0063', 'donor_percent_cd34l_thy1h_cdh11l: 0.0616', 'donor_percent_cd34l_thy1h_cdh11l: 0.0123'], 14: ['donor_percent_cd34l_thy1l_cdh11l: 0.216', 'donor_percent_cd34l_thy1l_cdh11l: 0.367', 'donor_percent_cd34l_thy1l_cdh11l: 0.151', 'donor_percent_cd34l_thy1l_cdh11l: 0.0797', 'donor_percent_cd34l_thy1l_cdh11l: 0.187', 'donor_percent_cd34l_thy1l_cdh11l: 0.133'], 15: ['donor_percent_cd34h_thy1l_cdh11h: 0.134', 'donor_percent_cd34h_thy1l_cdh11h: 0.251', 'donor_percent_cd34h_thy1l_cdh11h: 0.165', 'donor_percent_cd34h_thy1l_cdh11h: 0.0105', 'donor_percent_cd34h_thy1l_cdh11h: 0.199', 'donor_percent_cd34h_thy1l_cdh11h: 0.0095'], 16: ['donor_percent_cd34h_thy1h_cdh11h: 0.728', 'donor_percent_cd34h_thy1h_cdh11h: 0.6', 'donor_percent_cd34h_thy1h_cdh11h: 0.719', 'donor_percent_cd34h_thy1h_cdh11h: 0.882', 'donor_percent_cd34h_thy1h_cdh11h: 0.627', 'donor_percent_cd34h_thy1h_cdh11h: 0.929'], 17: ['donor_percent_cd34h_thy1h_cdh11l: NA', 'donor_percent_cd34h_thy1h_cdh11l: 0.0374', 'donor_percent_cd34h_thy1h_cdh11l: 0.0177', 'donor_percent_cd34h_thy1h_cdh11l: 0.0391', 'donor_percent_cd34h_thy1h_cdh11l: 0.0253', 'donor_percent_cd34h_thy1h_cdh11l: 0.0175'], 18: ['donor_percent_cd34h_thy1l_cdh11l: NA', 'donor_percent_cd34h_thy1l_cdh11l: 0.0459', 'donor_percent_cd34h_thy1l_cdh11l: 0.0154', 'donor_percent_cd34h_thy1l_cdh11l: 0.0033', 'donor_percent_cd34h_thy1l_cdh11l: 0.0188', 'donor_percent_cd34h_thy1l_cdh11l: 0.0011']}\n", "\n", "Values in trait row:\n", "['!Sample_characteristics_ch1' 'disease: OA' 'disease: OA' 'disease: OA'\n", " 'disease: OA']\n", "\n", "Created clinical features dataframe:\n", "Shape: (1, 36)\n", " GSM2861345 GSM2861346 GSM2861347 GSM2861348 GSM2861349\n", "Osteoarthritis 1 1 1 1 1\n", "\n", "Linked data shape before handling missing values: (36, 16347)\n", "Actual trait column in linked data: Osteoarthritis\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "/media/techt/DATA/GenoAgent/tools/preprocess.py:455: FutureWarning: Downcasting object dtype arrays on .fillna, .ffill, .bfill is deprecated and will change in a future version. Call result.infer_objects(copy=False) instead. To opt-in to the future behavior, set `pd.set_option('future.no_silent_downcasting', True)`\n", " df[gene_cols] = df[gene_cols].fillna(df[gene_cols].mean())\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data shape after handling missing values: (36, 16347)\n", "For the feature 'Osteoarthritis', the least common label is '1' with 15 occurrences. This represents 41.67% of the dataset.\n", "The distribution of the feature 'Osteoarthritis' in this dataset is fine.\n", "\n", "A new JSON file was created at: ../../output/preprocess/Osteoarthritis/cohort_info.json\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data saved to ../../output/preprocess/Osteoarthritis/GSE107105.csv\n" ] } ], "source": [ "# 1. Normalize gene symbols in the gene expression data \n", "# (This was already done in the previous step, so no need to repeat)\n", "print(f\"Normalized gene data shape: {gene_data.shape}\")\n", "\n", "# 2. Examine the sample IDs in the gene expression data to understand the structure\n", "print(\"Gene data column names (sample IDs):\")\n", "print(gene_data.columns[:5]) # Print first 5 for brevity\n", "\n", "# Inspect the clinical data format from the matrix file directly\n", "background_info, clinical_data = get_background_and_clinical_data(matrix_file)\n", "print(\"\\nRaw clinical data structure:\")\n", "print(f\"Clinical data shape: {clinical_data.shape}\")\n", "print(f\"Clinical data columns: {clinical_data.columns[:5]}\")\n", "\n", "# Get the sample characteristics to re-extract the disease information\n", "sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n", "print(\"\\nSample characteristics dictionary:\")\n", "print(sample_characteristics_dict)\n", "\n", "# 3. Directly create clinical features from the raw data again\n", "# Verify trait row contains the disease information (OA vs RA)\n", "print(\"\\nValues in trait row:\")\n", "trait_values = clinical_data.iloc[trait_row].values\n", "print(trait_values[:5])\n", "\n", "# Create clinical dataframe with proper structure\n", "# First get the sample IDs from gene data as these are our actual sample identifiers\n", "sample_ids = gene_data.columns.tolist()\n", "\n", "# Create the clinical features dataframe with those sample IDs\n", "clinical_features = pd.DataFrame(index=[trait], columns=sample_ids)\n", "\n", "# Fill the clinical features with our trait values by mapping GSM IDs to actual values\n", "for col in clinical_data.columns:\n", " if col in sample_ids:\n", " # Extract the disease value and convert it\n", " disease_val = clinical_data.iloc[trait_row][col]\n", " clinical_features.loc[trait, col] = convert_trait(disease_val)\n", "\n", "print(\"\\nCreated clinical features dataframe:\")\n", "print(f\"Shape: {clinical_features.shape}\")\n", "print(clinical_features.iloc[:, :5]) # Show first 5 columns\n", "\n", "# 4. Link clinical and genetic data\n", "linked_data = geo_link_clinical_genetic_data(clinical_features, gene_data)\n", "print(f\"\\nLinked data shape before handling missing values: {linked_data.shape}\")\n", "\n", "# 5. Handle missing values - we need to use the actual column name, not the trait variable\n", "# First identify the actual trait column name in the linked data\n", "trait_column = clinical_features.index[0] # This should be 'Osteoarthritis'\n", "print(f\"Actual trait column in linked data: {trait_column}\")\n", "\n", "# Now handle missing values with the correct column name\n", "linked_data_clean = handle_missing_values(linked_data, trait_column)\n", "print(f\"Linked data shape after handling missing values: {linked_data_clean.shape}\")\n", "\n", "# 6. Evaluate bias in trait and demographic features\n", "is_biased, linked_data_clean = judge_and_remove_biased_features(linked_data_clean, trait_column)\n", "\n", "# 7. Conduct final quality validation\n", "note = \"Dataset contains gene expression data from synovial fibroblasts of RA and OA patients. Data includes high serum and low serum responses.\"\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=(linked_data_clean.shape[0] > 0),\n", " is_biased=is_biased,\n", " df=linked_data_clean,\n", " note=note\n", ")\n", "\n", "# 8. Save linked data if usable\n", "if is_usable:\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " linked_data_clean.to_csv(out_data_file)\n", " print(f\"Linked data saved to {out_data_file}\")\n", "else:\n", " print(\"Dataset deemed not usable due to quality issues - 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 }