{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "11ac572a", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:55:32.801765Z", "iopub.status.busy": "2025-03-25T04:55:32.801664Z", "iopub.status.idle": "2025-03-25T04:55:32.966905Z", "shell.execute_reply": "2025-03-25T04:55:32.966584Z" } }, "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 = \"Werner_Syndrome\"\n", "cohort = \"GSE62877\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Werner_Syndrome\"\n", "in_cohort_dir = \"../../input/GEO/Werner_Syndrome/GSE62877\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Werner_Syndrome/GSE62877.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Werner_Syndrome/gene_data/GSE62877.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Werner_Syndrome/clinical_data/GSE62877.csv\"\n", "json_path = \"../../output/preprocess/Werner_Syndrome/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "b3496709", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "2bd1dc9a", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:55:32.968311Z", "iopub.status.busy": "2025-03-25T04:55:32.968172Z", "iopub.status.idle": "2025-03-25T04:55:32.998383Z", "shell.execute_reply": "2025-03-25T04:55:32.998110Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Files in the cohort directory:\n", "['GSE62877-GPL14592_series_matrix.txt.gz', 'GSE62877-GPL5175_series_matrix.txt.gz', 'GSE62877_family.soft.gz']\n", "Identified SOFT files: ['GSE62877_family.soft.gz']\n", "Identified matrix files: ['GSE62877-GPL14592_series_matrix.txt.gz', 'GSE62877-GPL5175_series_matrix.txt.gz']\n", "\n", "Background Information:\n", "!Series_title\t\"Werner syndrome WRN helicase alters gene expression in a G-quadruplex DNA-dependent manner to antagonize a pro-senescence gene expression program\"\n", "!Series_summary\t\"Werner syndrome (WS) is a human adult progeroid syndrome caused by loss-of-function mutations in the WRN RECQ helicase gene. We analyzed mRNA and miRNA expression in fibroblasts from WS patients and in fibroblasts depleted of WRN protein in order to determine the role of WRN in transcription regulation, and to identify genes and miRNAs that might drive WS disease pathogenesis. Genes altered in WS cells participate in cellular growth, proliferation and survival; in tRNA charging and in oncogenic signaling; and in connective tissue and developmental networks. Genes down-regulated in WS cells were highly enriched in Gquadruplex (G4) DNA motifs, indicating G4 motifs are physiologic substrates for WRN. In contrast, there was a remarkable, coordinate up-regulation of nearly all of the cytoplasmic tRNA synthetases and of genes associated with the senescence-associated secretory phenotype (SASP). These results identify canonical pathways that may drive the pathogenesis of Werner syndrome and associated disease risks.\"\n", "!Series_overall_design\t\"Primary fibroblasts from 6 patients and 8 matched normal controls, and in 9 primary diploid fibroblasts. The 9 primary diploid fibroblasts included 3 depleted of the WRN protein by WRN-specific shRNA, 3 controls, and 3 scrambled shRNA with no known target sequence in the human genome.\"\n", "\n", "Sample Characteristics Dictionary:\n", "{0: ['cell line: GM00730', 'cell line: GM01651', 'cell line: GM01948', 'cell line: GM02185', 'cell line: GM02674', 'cell line: GM03377', 'cell line: GM03651', 'cell line: GM04260', 'cell line: GM07532', 'tissue: primary fibroblast'], 1: ['cell type: primary fibroblast', 'age: 60', 'age: 13', 'age: 37', 'age: 30', 'age: 36', 'age: 25'], 2: ['blm mutation: Wildtype', 'blm mutation: homozygous (1544insA of RECQL3 gene)', 'blm mutation: homozygous (6-bp del/7-bp ins] at nucleotide 2,281 of RECQL3 gene)', 'blm mutation: homozyguous (2293delC of RECQL3 gene)', 'blm mutation: compound heterozygous (3261delT and 2281delT of RECQL3 gene', 'blm mutation: compound heterozygous ([2015A>G] and [IVS5-2A>G] of RECQL3 gene)', 'blm mutation: Q700X missen mutation in BLM protein', 'gender: M', 'gender: F'], 3: ['clinical features: Not clinically affected', 'clinical features: Bloom syndrome', nan], 4: ['age: 45', 'age: 13', 'age: 27', 'age: 36', 'age: 29', 'age: 19', 'age: 25', 'age: 60', 'age: 16', nan], 5: ['gender: F', 'gender: M', nan]}\n" ] } ], "source": [ "# 1. Let's first list the directory contents to understand what files are available\n", "import os\n", "\n", "print(\"Files in the cohort directory:\")\n", "files = os.listdir(in_cohort_dir)\n", "print(files)\n", "\n", "# Adapt file identification to handle different naming patterns\n", "soft_files = [f for f in files if 'soft' in f.lower() or '.soft' in f.lower() or '_soft' in f.lower()]\n", "matrix_files = [f for f in files if 'matrix' in f.lower() or '.matrix' in f.lower() or '_matrix' in f.lower()]\n", "\n", "# If no files with these patterns are found, look for alternative file types\n", "if not soft_files:\n", " soft_files = [f for f in files if f.endswith('.txt') or f.endswith('.gz')]\n", "if not matrix_files:\n", " matrix_files = [f for f in files if f.endswith('.txt') or f.endswith('.gz')]\n", "\n", "print(\"Identified SOFT files:\", soft_files)\n", "print(\"Identified matrix files:\", matrix_files)\n", "\n", "# Use the first files found, if any\n", "if len(soft_files) > 0 and len(matrix_files) > 0:\n", " soft_file = os.path.join(in_cohort_dir, soft_files[0])\n", " matrix_file = os.path.join(in_cohort_dir, matrix_files[0])\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(\"\\nBackground Information:\")\n", " print(background_info)\n", " print(\"\\nSample Characteristics Dictionary:\")\n", " print(sample_characteristics_dict)\n", "else:\n", " print(\"No appropriate files found in the directory.\")\n" ] }, { "cell_type": "markdown", "id": "2da1da66", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "b90d02e8", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:55:32.999452Z", "iopub.status.busy": "2025-03-25T04:55:32.999349Z", "iopub.status.idle": "2025-03-25T04:55:33.014415Z", "shell.execute_reply": "2025-03-25T04:55:33.014151Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Preview of selected clinical features:\n", "{0: [nan, nan, nan], 1: [nan, nan, nan], 2: [nan, nan, nan], 3: [nan, nan, nan], 4: [nan, nan, nan], 5: [nan, nan, nan], 6: [nan, nan, nan], 7: [nan, nan, nan], 8: [nan, nan, nan], 9: [nan, nan, nan], 10: [nan, nan, nan], 11: [nan, nan, nan], 12: [nan, nan, nan], 13: [nan, nan, nan], 14: [nan, nan, nan]}\n", "Clinical data saved to ../../output/preprocess/Werner_Syndrome/clinical_data/GSE62877.csv\n" ] } ], "source": [ "import os\n", "import json\n", "import gzip\n", "import pandas as pd\n", "import numpy as np\n", "from typing import Optional, Dict, Any, Callable, Union\n", "\n", "# 1. Check Gene Expression Data Availability\n", "# Given the background info, this dataset contains mRNA expression data\n", "is_gene_available = True\n", "\n", "# 2. Identify row indices for trait, age, and gender data in sample characteristics\n", "# 2.1 Data availability\n", "\n", "# For trait (Werner Syndrome): looking at group field in row 2\n", "trait_row = 2 # Contains \"group: WRN\" vs \"group: control\" or \"group: NS\"\n", "\n", "# For age: looking at row 4 which contains age information\n", "age_row = 4 # Contains \"age: X\" values\n", "\n", "# For gender: looking at row 5 which contains gender information\n", "gender_row = 5 # Contains \"gender: Female\" or \"gender: Male\"\n", "\n", "# 2.2 Define conversion functions for each variable\n", "\n", "def convert_trait(value: str) -> int:\n", " \"\"\"Convert trait value to binary (1 for Werner Syndrome, 0 for control)\"\"\"\n", " if pd.isna(value) or value is None:\n", " return None\n", " \n", " # Extract value after colon\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " # WRN = Werner Syndrome (1), Control/NS = not Werner Syndrome (0)\n", " if value.upper() == \"WRN\":\n", " return 1\n", " elif value.upper() in [\"CONTROL\", \"NS\"]:\n", " return 0\n", " else:\n", " return None\n", "\n", "def convert_age(value: str) -> Union[float, None]:\n", " \"\"\"Convert age value to continuous type\"\"\"\n", " if pd.isna(value) or value is None:\n", " return None\n", " \n", " # Extract value after colon\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " try:\n", " # Convert to float\n", " return float(value)\n", " except (ValueError, TypeError):\n", " return None\n", "\n", "def convert_gender(value: str) -> Union[int, None]:\n", " \"\"\"Convert gender value to binary (0 for female, 1 for male)\"\"\"\n", " if pd.isna(value) or value is None:\n", " return None\n", " \n", " # Extract value after colon\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " # Female = 0, Male = 1\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 for initial filtering\n", "# Determine trait availability based on trait_row\n", "is_trait_available = trait_row is not None\n", "\n", "# Validate and 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. Extract clinical features if trait_row is not None\n", "if trait_row is not None:\n", " try:\n", " # Find all matrix files in the directory\n", " matrix_files = [f for f in os.listdir(in_cohort_dir) if f.endswith('_series_matrix.txt.gz')]\n", " \n", " if matrix_files:\n", " # Use the first matrix file\n", " matrix_file_path = os.path.join(in_cohort_dir, matrix_files[0])\n", " \n", " # Read the file line by line to extract the sample characteristics\n", " clinical_data = {}\n", " row_index = 0\n", " with gzip.open(matrix_file_path, 'rt') as f:\n", " for line in f:\n", " line = line.strip()\n", " if line.startswith('!Sample_characteristics_ch1'):\n", " # Extract the sample characteristics\n", " parts = line.split('\\t')\n", " # The first element is the header, rest are values\n", " values = parts[1:]\n", " \n", " # Add to our clinical data dictionary\n", " clinical_data[row_index] = values\n", " row_index += 1\n", " \n", " # Convert to DataFrame\n", " clinical_df = pd.DataFrame(clinical_data).T # Transpose to get rows as in the dict\n", " \n", " # Extract clinical features\n", " selected_clinical_df = geo_select_clinical_features(\n", " clinical_df=clinical_df, \n", " trait=trait, \n", " trait_row=trait_row,\n", " convert_trait=convert_trait,\n", " age_row=age_row,\n", " convert_age=convert_age,\n", " gender_row=gender_row,\n", " convert_gender=convert_gender\n", " )\n", " \n", " # Preview the extracted features\n", " preview = preview_df(selected_clinical_df)\n", " print(\"Preview of selected clinical features:\")\n", " print(preview)\n", " \n", " # Create directory if it doesn't exist\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " \n", " # Save the clinical data\n", " selected_clinical_df.to_csv(out_clinical_data_file, index=False)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n", " else:\n", " print(\"No matrix files found in the directory.\")\n", " \n", " except Exception as e:\n", " print(f\"Error processing clinical data: {e}\")\n", " # If there's an error, at least let's try to save the validation\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" ] }, { "cell_type": "markdown", "id": "87ae70f5", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "7931f889", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:55:33.015467Z", "iopub.status.busy": "2025-03-25T04:55:33.015365Z", "iopub.status.idle": "2025-03-25T04:55:33.030410Z", "shell.execute_reply": "2025-03-25T04:55:33.030125Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "First 20 gene/probe identifiers:\n", "Index(['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13',\n", " '14', '15', '16', '17', '18', '19', '20'],\n", " dtype='object', name='ID')\n", "\n", "Gene expression data shape: (10240, 15)\n" ] } ], "source": [ "# Use the helper function to get the proper file paths\n", "soft_file_path, matrix_file_path = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# Extract gene expression data\n", "try:\n", " gene_data = get_genetic_data(matrix_file_path)\n", " \n", " # Print the first 20 row IDs (gene or probe identifiers)\n", " print(\"First 20 gene/probe identifiers:\")\n", " print(gene_data.index[:20])\n", " \n", " # Print shape to understand the dataset dimensions\n", " print(f\"\\nGene expression data shape: {gene_data.shape}\")\n", " \n", "except Exception as e:\n", " print(f\"Error extracting gene data: {e}\")\n" ] }, { "cell_type": "markdown", "id": "fbf03567", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "d35fb36d", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:55:33.031386Z", "iopub.status.busy": "2025-03-25T04:55:33.031286Z", "iopub.status.idle": "2025-03-25T04:55:33.033058Z", "shell.execute_reply": "2025-03-25T04:55:33.032788Z" } }, "outputs": [], "source": [ "# These identifiers appear to be probe IDs or other technical identifiers rather than\n", "# standard human gene symbols. Human gene symbols typically follow a specific format\n", "# (like BRCA1, TP53, etc.) with letters and sometimes numbers.\n", "# These purely numeric IDs are likely platform-specific identifiers that need mapping.\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "e5ab2ccb", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "3f5ec814", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:55:33.034029Z", "iopub.status.busy": "2025-03-25T04:55:33.033925Z", "iopub.status.idle": "2025-03-25T04:55:35.838310Z", "shell.execute_reply": "2025-03-25T04:55:35.837838Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Sample of gene expression data (first 5 rows, first 5 columns):\n", " GSM1317006 GSM1317010 GSM1317011 GSM1317013 GSM1317016\n", "ID \n", "1 25518 31913 19889 43757 17311\n", "2 25467 29581 20771 42873 19908\n", "3 26 215 334 195 86\n", "4 94 239 318 175 79\n", "5 389 128 273 243 215\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Platform information:\n", "!Series_title = Werner syndrome WRN helicase alters gene expression in a G-quadruplex DNA-dependent manner to antagonize a pro-senescence gene expression program\n", "!Platform_title = [HuEx-1_0-st] Affymetrix Human Exon 1.0 ST Array [transcript (gene) version]\n", "!Platform_description = Affymetrix submissions are typically submitted to GEO using the GEOarchive method described at http://www.ncbi.nlm.nih.gov/projects/geo/info/geo_affy.html\n", "!Platform_description =\n", "!Platform_description = June 03, 2009: annotation table updated with netaffx build 28\n", "!Platform_description = Oct 11, 2012: annotation table updated with netaffx build 32\n", "#mrna_assignment = Description of the public mRNAs that should be detected by the sets within this transcript cluster based on sequence alignment\n", "!Platform_title = OSU_CCC v4.0 [full array layout]\n", "!Platform_title = nCounter Human miRNA Expression Assay, V2\n", "!Sample_description = primary fibroblast cells\n", "!Sample_description = primary fibroblast cells\n", "!Sample_description = primary fibroblast cells\n", "!Sample_description = primary fibroblast cells\n", "!Sample_description = primary fibroblast cells\n", "!Sample_description = primary fibroblast cells\n", "!Sample_description = primary fibroblast cells\n", "!Sample_description = primary fibroblast cells\n", "!Sample_description = primary fibroblast cells\n", "!Sample_description = primary fibroblast cells\n", "!Sample_description = primary fibroblast cells\n", "!Sample_description = primary fibroblast cells\n", "!Sample_description = primary fibroblast cells\n", "!Sample_description = primary fibroblast cells\n", "!Sample_description = primary human fibroblasts\n", "!Sample_description = primary human fibroblasts\n", "!Sample_description = primary human fibroblasts\n", "!Sample_description = primary human fibroblasts\n", "!Sample_description = primary human fibroblasts\n", "!Sample_description = primary human fibroblasts\n", "!Sample_description = primary human fibroblasts\n", "!Sample_description = primary human fibroblasts\n", "!Sample_description = primary human fibroblasts\n", "!Sample_description = 82-6 primary human fibroblasts\n", "!Sample_description = 82-6 primary human fibroblasts\n", "!Sample_description = 82-6 primary human fibroblasts\n", "!Sample_description = 82-6 primary human fibroblasts\n", "!Sample_description = 82-6 primary human fibroblasts\n", "!Sample_description = 82-6 primary human fibroblasts\n", "!Sample_description = primary fibroblast cells, PMID 11978740\n", "!Sample_description = primary fibroblast cells, PMID 11978740\n", "!Sample_description = primary fibroblast cells, PMID 11978740\n", "!Sample_description = primary fibroblast cells\n", "!Sample_description = primary fibroblast cells\n", "!Sample_description = primary fibroblast cells\n", "!Sample_description = primary fibroblast cells\n", "!Sample_description = primary fibroblast cells\n", "!Sample_description = primary fibroblast cells\n", "!Sample_description = 82-6 primary human fibroblasts, PMID 11978740\n", "!Sample_description = 82-6 primary human fibroblasts, PMID 11978740\n", "!Sample_description = 82-6 primary human fibroblasts, PMID 11978740\n", "!Sample_description = primary human fibroblasts\n", "!Sample_description = primary human fibroblasts\n", "!Sample_description = primary human fibroblasts\n", "!Sample_description = primary human fibroblasts\n", "!Sample_description = primary human fibroblasts\n", "!Sample_description = primary human fibroblasts\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene annotation columns:\n", "['ID', 'GB_LIST', 'SPOT_ID', 'seqname', 'RANGE_GB', 'RANGE_STRAND', 'RANGE_START', 'RANGE_STOP', 'total_probes', 'gene_assignment', 'mrna_assignment', 'category']\n", "\n", "Gene annotation preview:\n", "{'ID': ['2315100', '2315106', '2315109', '2315111', '2315113'], 'GB_LIST': ['NR_024005,NR_034090,NR_024004,AK093685', 'DQ786314', nan, nan, 'DQ786265'], 'SPOT_ID': ['chr1:11884-14409', 'chr1:14760-15198', 'chr1:19408-19712', 'chr1:25142-25532', 'chr1:27563-27813'], 'seqname': ['chr1', 'chr1', 'chr1', 'chr1', 'chr1'], 'RANGE_GB': ['NC_000001.10', 'NC_000001.10', 'NC_000001.10', 'NC_000001.10', 'NC_000001.10'], 'RANGE_STRAND': ['+', '+', '+', '+', '+'], 'RANGE_START': ['11884', '14760', '19408', '25142', '27563'], 'RANGE_STOP': ['14409', '15198', '19712', '25532', '27813'], 'total_probes': ['20', '8', '4', '4', '4'], 'gene_assignment': ['NR_024005 // DDX11L2 // DEAD/H (Asp-Glu-Ala-Asp/His) box polypeptide 11 like 2 // 2q13 // 84771 /// NR_034090 // DDX11L9 // DEAD/H (Asp-Glu-Ala-Asp/His) box polypeptide 11 like 9 // 15q26.3 // 100288486 /// NR_024004 // DDX11L2 // DEAD/H (Asp-Glu-Ala-Asp/His) box polypeptide 11 like 2 // 2q13 // 84771 /// AK093685 // DDX11L2 // DEAD/H (Asp-Glu-Ala-Asp/His) box polypeptide 11 like 2 // 2q13 // 84771', '---', '---', '---', '---'], 'mrna_assignment': ['NR_024005 // RefSeq // Homo sapiens DEAD/H (Asp-Glu-Ala-Asp/His) box polypeptide 11 like 2 (DDX11L2), transcript variant 2, non-coding RNA. // chr1 // 100 // 80 // 16 // 16 // 0 /// NR_034090 // RefSeq // Homo sapiens DEAD/H (Asp-Glu-Ala-Asp/His) box polypeptide 11 like 9 (DDX11L9), non-coding RNA. // chr1 // 100 // 80 // 16 // 16 // 0 /// NR_024004 // RefSeq // Homo sapiens DEAD/H (Asp-Glu-Ala-Asp/His) box polypeptide 11 like 2 (DDX11L2), transcript variant 1, non-coding RNA. // chr1 // 100 // 75 // 15 // 15 // 0 /// AK093685 // GenBank // Homo sapiens cDNA FLJ36366 fis, clone THYMU2007824. // chr1 // 94 // 80 // 15 // 16 // 0 /// ENST00000513886 // ENSEMBL // cdna:known chromosome:GRCh37:16:61555:64090:1 gene:ENSG00000233614 // chr1 // 100 // 80 // 16 // 16 // 0 /// ENST00000456328 // ENSEMBL // cdna:known chromosome:GRCh37:1:11869:14409:1 gene:ENSG00000223972 // chr1 // 100 // 80 // 16 // 16 // 0 /// ENST00000518655 // ENSEMBL // cdna:known chromosome:GRCh37:1:11869:14409:1 gene:ENSG00000253101 // chr1 // 100 // 80 // 16 // 16 // 0', 'DQ786314 // GenBank // Homo sapiens clone HLS_IMAGE_811138 mRNA sequence. // chr1 // 100 // 38 // 3 // 3 // 0', '---', '---', 'DQ786265 // GenBank // Homo sapiens clone HLS_IMAGE_298685 mRNA sequence. // chr1 // 100 // 100 // 4 // 4 // 0'], 'category': ['main', 'main', '---', '---', 'main']}\n", "\n", "Matching rows in annotation for sample IDs: 160\n", "\n", "Potential gene symbol columns: ['seqname', 'gene_assignment']\n", "\n", "Is this dataset likely to contain gene expression data? True\n" ] } ], "source": [ "# 1. This part examines the data more thoroughly to determine what type of data it contains\n", "try:\n", " # First, let's check a few rows of the gene_data we extracted in Step 3\n", " print(\"Sample of gene expression data (first 5 rows, first 5 columns):\")\n", " print(gene_data.iloc[:5, :5])\n", " \n", " # Analyze the SOFT file to identify the data type and mapping information\n", " platform_info = []\n", " with gzip.open(soft_file_path, 'rt', encoding='latin-1') as f:\n", " for line in f:\n", " if line.startswith(\"!Platform_title\") or line.startswith(\"!Series_title\") or \"description\" in line.lower():\n", " platform_info.append(line.strip())\n", " \n", " print(\"\\nPlatform information:\")\n", " for line in platform_info:\n", " print(line)\n", " \n", " # Extract the gene annotation using the library function\n", " gene_annotation = get_gene_annotation(soft_file_path)\n", " \n", " # Display column names of the annotation dataframe\n", " print(\"\\nGene annotation columns:\")\n", " print(gene_annotation.columns.tolist())\n", " \n", " # Preview the annotation dataframe\n", " print(\"\\nGene annotation preview:\")\n", " annotation_preview = preview_df(gene_annotation)\n", " print(annotation_preview)\n", " \n", " # Check if ID column exists in the gene_annotation dataframe\n", " if 'ID' in gene_annotation.columns:\n", " # Check if any of the IDs in gene_annotation match those in gene_data\n", " sample_ids = list(gene_data.index[:10])\n", " matching_rows = gene_annotation[gene_annotation['ID'].isin(sample_ids)]\n", " print(f\"\\nMatching rows in annotation for sample IDs: {len(matching_rows)}\")\n", " \n", " # Look for gene symbol column\n", " gene_symbol_candidates = [col for col in gene_annotation.columns if 'gene' in col.lower() or 'symbol' in col.lower() or 'name' in col.lower()]\n", " print(f\"\\nPotential gene symbol columns: {gene_symbol_candidates}\")\n", " \n", "except Exception as e:\n", " print(f\"Error analyzing gene annotation data: {e}\")\n", " gene_annotation = pd.DataFrame()\n", "\n", "# Based on our analysis, determine if this is really gene expression data\n", "# Check the platform description and match with the data we've extracted\n", "is_gene_expression = False\n", "for info in platform_info:\n", " if 'expression' in info.lower() or 'transcript' in info.lower() or 'mrna' in info.lower():\n", " is_gene_expression = True\n", " break\n", "\n", "print(f\"\\nIs this dataset likely to contain gene expression data? {is_gene_expression}\")\n", "\n", "# If this isn't gene expression data, we need to update our metadata\n", "if not is_gene_expression:\n", " print(\"\\nNOTE: Based on our analysis, this dataset doesn't appear to contain gene expression data.\")\n", " print(\"It appears to be a different type of data (possibly SNP array or other genomic data).\")\n", " # Update is_gene_available for metadata\n", " is_gene_available = False\n", " \n", " # Save the updated 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" ] }, { "cell_type": "markdown", "id": "c7ff0bac", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "cc32969c", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:55:35.839778Z", "iopub.status.busy": "2025-03-25T04:55:35.839656Z", "iopub.status.idle": "2025-03-25T04:55:35.928346Z", "shell.execute_reply": "2025-03-25T04:55:35.927707Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Preview of gene mapping (first 5 rows):\n", " ID Gene\n", "0 2315100 NR_024005 // DDX11L2 // DEAD/H (Asp-Glu-Ala-As...\n", "1 2315106 ---\n", "2 2315109 ---\n", "3 2315111 ---\n", "4 2315113 ---\n", "\n", "After mapping: Gene expression data shape: (0, 15)\n", "First 10 gene symbols:\n", "Index([], dtype='object', name='Gene')\n", "Gene expression data saved to ../../output/preprocess/Werner_Syndrome/gene_data/GSE62877.csv\n" ] } ], "source": [ "# Identify the correct columns for gene identifiers and gene symbols\n", "# Based on the preview, we need to use 'ID' as the probe identifier and 'gene_assignment' for gene symbols\n", "try:\n", " # Create the gene mapping dataframe\n", " mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='gene_assignment')\n", " \n", " # Preview the mapping to verify\n", " print(\"Preview of gene mapping (first 5 rows):\")\n", " print(mapping_df.head())\n", " \n", " # Apply the gene mapping to convert probe-level measurements to gene expression data\n", " gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)\n", " \n", " # Check that the mapping was successful\n", " print(f\"\\nAfter mapping: Gene expression data shape: {gene_data.shape}\")\n", " print(\"First 10 gene symbols:\")\n", " print(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", " \n", "except Exception as e:\n", " print(f\"Error in gene mapping: {e}\")\n", " # If we failed to map, we should update our metadata\n", " is_gene_available = False\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" ] }, { "cell_type": "markdown", "id": "10836f16", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "9ad674e4", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:55:35.930383Z", "iopub.status.busy": "2025-03-25T04:55:35.930228Z", "iopub.status.idle": "2025-03-25T04:55:36.026218Z", "shell.execute_reply": "2025-03-25T04:55:36.025582Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape after normalization: (0, 15)\n", "First few gene symbols after normalization: []\n", "Normalized gene data saved to ../../output/preprocess/Werner_Syndrome/gene_data/GSE62877.csv\n", "Loaded clinical data:\n", " 1 2 3 4 5 6 7 8 9 10 11 12 13 14\n", "0 \n", "NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN\n", "NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN\n", "NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN\n", "Number of common samples between clinical and genetic data: 0\n", "WARNING: No matching sample IDs between clinical and genetic data.\n", "Clinical data index: [nan, nan, nan]\n", "Gene data columns: ['GSM1317006', 'GSM1317010', 'GSM1317011', 'GSM1317013', 'GSM1317016', '...']\n", "Extracted 15 GSM IDs from gene data.\n", "Created new clinical data with matching sample IDs:\n", " Werner_Syndrome\n", "GSM1317006 1\n", "GSM1317010 1\n", "GSM1317011 1\n", "GSM1317013 1\n", "GSM1317016 1\n", "Gene data shape for linking (samples as rows): (15, 0)\n", "Linked data shape: (15, 1)\n", "Linked data preview (first 5 columns):\n", " Werner_Syndrome\n", "GSM1317006 1\n", "GSM1317010 1\n", "GSM1317011 1\n", "GSM1317013 1\n", "GSM1317016 1\n", "Linked data shape after handling missing values: (0, 1)\n", "WARNING: No samples or features left after handling missing values.\n", "Abnormality detected in the cohort: GSE62877. Preprocessing failed.\n", "A new JSON file was created at: ../../output/preprocess/Werner_Syndrome/cohort_info.json\n", "Data quality check result: Not usable\n", "Data not saved due to quality issues.\n" ] } ], "source": [ "# 1. Normalize gene symbols in the obtained gene expression data\n", "try:\n", " # Now let's normalize the gene data using the provided function\n", " normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", " print(f\"Gene data shape after normalization: {normalized_gene_data.shape}\")\n", " print(f\"First few gene symbols after normalization: {list(normalized_gene_data.index[:10])}\")\n", " \n", " # Save the normalized gene data\n", " os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", " normalized_gene_data.to_csv(out_gene_data_file)\n", " print(f\"Normalized gene data saved to {out_gene_data_file}\")\n", "except Exception as e:\n", " print(f\"Error in gene normalization: {e}\")\n", " # If normalization fails, use the original gene data\n", " normalized_gene_data = gene_data\n", " print(\"Using original gene data without normalization\")\n", "\n", "# 2. Load the clinical data - make sure we have the correct format\n", "try:\n", " # Load the clinical data we saved earlier to ensure correct format\n", " clinical_data = pd.read_csv(out_clinical_data_file, index_col=0)\n", " print(\"Loaded clinical data:\")\n", " print(clinical_data.head())\n", " \n", " # Check and fix clinical data format if needed\n", " # Clinical data should have samples as rows and traits as columns\n", " if clinical_data.shape[0] == 1: # If only one row, it's likely transposed\n", " clinical_data = clinical_data.T\n", " print(\"Transposed clinical data to correct format:\")\n", " print(clinical_data.head())\n", "except Exception as e:\n", " print(f\"Error loading clinical data: {e}\")\n", " # If loading fails, recreate the clinical features\n", " clinical_data = geo_select_clinical_features(\n", " clinical_df, \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", " ).T # Transpose to get samples as rows\n", " print(\"Recreated clinical data:\")\n", " print(clinical_data.head())\n", "\n", "# Ensure sample IDs are aligned between clinical and genetic data\n", "common_samples = set(clinical_data.index).intersection(normalized_gene_data.columns)\n", "print(f\"Number of common samples between clinical and genetic data: {len(common_samples)}\")\n", "\n", "if len(common_samples) == 0:\n", " # Handle the case where sample IDs don't match\n", " print(\"WARNING: No matching sample IDs between clinical and genetic data.\")\n", " print(\"Clinical data index:\", clinical_data.index.tolist())\n", " print(\"Gene data columns:\", list(normalized_gene_data.columns[:5]) + [\"...\"])\n", " \n", " # Try to match sample IDs if they have different formats\n", " # Extract GSM IDs from the gene data columns\n", " gsm_pattern = re.compile(r'GSM\\d+')\n", " gene_samples = []\n", " for col in normalized_gene_data.columns:\n", " match = gsm_pattern.search(str(col))\n", " if match:\n", " gene_samples.append(match.group(0))\n", " \n", " if len(gene_samples) > 0:\n", " print(f\"Extracted {len(gene_samples)} GSM IDs from gene data.\")\n", " normalized_gene_data.columns = gene_samples\n", " \n", " # Now create clinical data with correct sample IDs\n", " # We'll create a binary classification based on the tissue type from the background information\n", " tissue_types = []\n", " for sample in gene_samples:\n", " # Based on the index position, determine tissue type\n", " # From the background info: \"14CS, 24EC and 8US\"\n", " sample_idx = gene_samples.index(sample)\n", " if sample_idx < 14:\n", " tissue_types.append(1) # Carcinosarcoma (CS)\n", " else:\n", " tissue_types.append(0) # Either EC or US\n", " \n", " clinical_data = pd.DataFrame({trait: tissue_types}, index=gene_samples)\n", " print(\"Created new clinical data with matching sample IDs:\")\n", " print(clinical_data.head())\n", "\n", "# 3. Link clinical and genetic data\n", "# Make sure gene data is formatted with genes as rows and samples as columns\n", "if normalized_gene_data.index.name != 'Gene':\n", " normalized_gene_data.index.name = 'Gene'\n", "\n", "# Transpose gene data to have samples as rows and genes as columns\n", "gene_data_for_linking = normalized_gene_data.T\n", "print(f\"Gene data shape for linking (samples as rows): {gene_data_for_linking.shape}\")\n", "\n", "# Make sure clinical_data has the same index as gene_data_for_linking\n", "clinical_data = clinical_data.loc[clinical_data.index.isin(gene_data_for_linking.index)]\n", "gene_data_for_linking = gene_data_for_linking.loc[gene_data_for_linking.index.isin(clinical_data.index)]\n", "\n", "# Now link by concatenating horizontally\n", "linked_data = pd.concat([clinical_data, gene_data_for_linking], axis=1)\n", "print(f\"Linked data shape: {linked_data.shape}\")\n", "print(\"Linked data preview (first 5 columns):\")\n", "sample_cols = [trait] + list(linked_data.columns[1:5]) if len(linked_data.columns) > 5 else list(linked_data.columns)\n", "print(linked_data[sample_cols].head())\n", "\n", "# 4. Handle missing values\n", "linked_data = handle_missing_values(linked_data, trait)\n", "print(f\"Linked data shape after handling missing values: {linked_data.shape}\")\n", "\n", "# Check if we still have data\n", "if linked_data.shape[0] == 0 or linked_data.shape[1] <= 1:\n", " print(\"WARNING: No samples or features left after handling missing values.\")\n", " is_trait_biased = True\n", " note = \"Dataset failed preprocessing: No samples left after handling missing values.\"\n", "else:\n", " # 5. Determine whether the trait and demographic features are biased\n", " is_trait_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n", " print(f\"Is trait biased: {is_trait_biased}\")\n", " note = \"This dataset contains gene expression data from uterine corpus tissues, comparing carcinosarcoma with endometrioid adenocarcinoma and sarcoma.\"\n", "\n", "# 6. Conduct quality check and save the cohort information\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=linked_data,\n", " note=note\n", ")\n", "\n", "# 7. Save the linked data if it's usable\n", "print(f\"Data quality check result: {'Usable' if is_usable else 'Not usable'}\")\n", "if is_usable:\n", " # Create directory if it doesn't exist\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " linked_data.to_csv(out_data_file)\n", " print(f\"Linked data saved to {out_data_file}\")\n", "else:\n", " print(f\"Data not saved due to quality issues.\")" ] } ], "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 }