{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "66a30226", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:55:25.113936Z", "iopub.status.busy": "2025-03-25T04:55:25.113710Z", "iopub.status.idle": "2025-03-25T04:55:25.279120Z", "shell.execute_reply": "2025-03-25T04:55:25.278807Z" } }, "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 = \"Von_Willebrand_Disease\"\n", "cohort = \"GSE27597\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Von_Willebrand_Disease\"\n", "in_cohort_dir = \"../../input/GEO/Von_Willebrand_Disease/GSE27597\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Von_Willebrand_Disease/GSE27597.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Von_Willebrand_Disease/gene_data/GSE27597.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Von_Willebrand_Disease/clinical_data/GSE27597.csv\"\n", "json_path = \"../../output/preprocess/Von_Willebrand_Disease/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "9e2a9a2f", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "df3d6b0a", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:55:25.280479Z", "iopub.status.busy": "2025-03-25T04:55:25.280348Z", "iopub.status.idle": "2025-03-25T04:55:25.325381Z", "shell.execute_reply": "2025-03-25T04:55:25.325068Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Files in the cohort directory:\n", "['GSE27597-GPL13243_series_matrix.txt.gz', 'GSE27597-GPL5175_series_matrix.txt.gz', 'GSE27597_family.soft.gz']\n", "Identified SOFT files: ['GSE27597_family.soft.gz']\n", "Identified matrix files: ['GSE27597-GPL13243_series_matrix.txt.gz', 'GSE27597-GPL5175_series_matrix.txt.gz']\n", "\n", "Background Information:\n", "!Series_title\t\"A gene expression signature of emphysema-related lung destruction and its reversal by the tripeptide GHK.\"\n", "!Series_summary\t\"BACKGROUND: Chronic obstructive pulmonary disease (COPD) is a heterogeneous disease consisting of emphysema, small airway obstruction, and/or chronic bronchitis that results in significant loss of lung function over time. METHODS: In order to gain insights into the molecular pathways underlying progression of emphysema and explore computational strategies for identifying COPD therapeutics, we profiled gene expression in lung tissue samples obtained from regions within the same lung with varying amounts of emphysematous destruction from smokers with COPD (8 regions x 8 lungs = 64 samples). Regional emphysema severity was quantified in each tissue sample using the mean linear intercept (Lm) between alveolar walls from micro-CT scans. RESULTS: We identified 127 genes whose expression levels were significantly associated with regional emphysema severity while controlling for gene expression differences between individuals. Genes increasing in expression with increasing emphysematous destruction included those involved in inflammation, such as the B-cell receptor signaling pathway, while genes decreasing in expression were enriched in tissue repair processes, including the transforming growth factor beta (TGF beta) pathway, actin organization, and integrin signaling. We found concordant differential expression of these emphysema severity-associated genes in four cross-sectional studies of COPD. Using the Connectivity Map, we identified GHK as a compound that can reverse the gene-expression signature associated with emphysematous destruction and induce expression patterns consistent with TGF beta pathway activation. Treatment of human fibroblasts with GHK recapitulated TGF beta-induced gene-expression patterns, led to the organization of the actin cytoskeleton, and elevated the expression of integrin beta1. Furthermore, addition of GHK or TGF beta restored collagen I contraction and remodeling by fibroblasts derived from COPD lungs compared to fibroblasts from former smokers without COPD. CONCLUSIONS: These results demonstrate that gene-expression changes associated with regional emphysema severity within an individual¿s lung can provide insights into emphysema pathogenesis and identify novel therapeutic opportunities for this deadly disease. They also suggest the need for additional studies to examine the mechanisms by which TGF beta and GHK each reverse the gene-expression signature of emphysematous destruction and the effects of this reversal on disease progression.\"\n", "!Series_overall_design\t\"Paired samples were obtained from 8 regions at regular intervals between the apex and base of each explanted lung from six patients with severe COPD and two donors. The degree of emphysematous destruction was quantified in one sample from each region by mean linear intercept (Lm), while gene expression was profiled in the adjacent sample from the same region using the Affymetrix Human Exon 1.0 ST GeneChip. Human fibroblast cell lines (HLF-1) were treated with GHK or TGF-Beta1 for 48 hours and profiled using the Affymetrix Human Gene 1.0 ST GeneChip.\"\n", "\n", "Sample Characteristics Dictionary:\n", "{0: ['time: 48hrs'], 1: ['ghk: 10nM', 'ghk: 0', 'ghk: 0.1nM'], 2: ['tgfb1: 0', 'tgfb1: 10 ng/ul']}\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": "35a772cc", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "fa1187d1", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:55:25.326526Z", "iopub.status.busy": "2025-03-25T04:55:25.326423Z", "iopub.status.idle": "2025-03-25T04:55:25.346288Z", "shell.execute_reply": "2025-03-25T04:55:25.345978Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Preview of selected clinical features:\n", "{0: [0.0, nan, nan], 1: [0.0, nan, nan], 2: [0.0, nan, nan]}\n", "Clinical data saved to ../../output/preprocess/Von_Willebrand_Disease/clinical_data/GSE27597.csv\n" ] } ], "source": [ "# 1. Gene Expression Data Availability\n", "# Based on the series title and summary, this dataset contains gene expression data\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "# For trait: Von_Willebrand_Disease can be inferred from notes (row 7)\n", "trait_row = 7\n", "# Age is available in row 5\n", "age_row = 5\n", "# Gender is available in row 4\n", "gender_row = 4\n", "\n", "# 2.2 Data Type Conversion Functions\n", "def convert_trait(value):\n", " \"\"\"Convert Von Willebrand Disease status to binary format.\"\"\"\n", " if \":\" not in value:\n", " return None\n", " notes = value.split(\":\", 1)[1].strip().lower()\n", " # Check if \"von willebrand disease\" is in the notes\n", " if \"von willebrand disease\" in notes:\n", " return 1\n", " return 0\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age to continuous format.\"\"\"\n", " if \":\" not in value:\n", " return None\n", " age_str = value.split(\":\", 1)[1].strip()\n", " try:\n", " return float(age_str)\n", " except ValueError:\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender to binary format (0 for female, 1 for male).\"\"\"\n", " if \":\" not in value:\n", " return None\n", " gender = value.split(\":\", 1)[1].strip().lower()\n", " if \"female\" in gender:\n", " return 0\n", " elif \"male\" in gender:\n", " return 1\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Determine trait data availability\n", "is_trait_available = trait_row is not None\n", "# Save initial cohort info\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", "# Since trait_row is not None, we need to extract clinical features\n", "if trait_row is not None:\n", " # Load clinical data from the previous step\n", " # First find the appropriate matrix file\n", " matrix_files = [f for f in os.listdir(in_cohort_dir) if f.endswith('series_matrix.txt.gz')]\n", " matrix_file = os.path.join(in_cohort_dir, matrix_files[0]) # Use the first matrix file\n", " \n", " # Read the sample characteristics from the matrix file\n", " clinical_data = pd.DataFrame()\n", " with gzip.open(matrix_file, 'rt') as f:\n", " lines = []\n", " reading_characteristics = False\n", " for line in f:\n", " if line.startswith('!Sample_characteristics_ch1'):\n", " reading_characteristics = True\n", " lines.append(line)\n", " elif reading_characteristics and not line.startswith('!Sample_characteristics_ch1'):\n", " reading_characteristics = False\n", " \n", " # Process the sample characteristics lines\n", " if lines:\n", " data = [line.strip().split('\\t')[1:] for line in lines]\n", " clinical_data = pd.DataFrame(data).T\n", " \n", " # Extract clinical features using the library function\n", " selected_clinical_df = geo_select_clinical_features(\n", " clinical_df=clinical_data,\n", " trait=trait,\n", " trait_row=trait_row,\n", " convert_trait=convert_trait,\n", " age_row=age_row,\n", " convert_age=convert_age,\n", " gender_row=gender_row,\n", " convert_gender=convert_gender\n", " )\n", " \n", " # Preview the output\n", " print(\"Preview of selected clinical features:\")\n", " print(preview_df(selected_clinical_df))\n", " \n", " # Save the clinical data to the output file\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " selected_clinical_df.to_csv(out_clinical_data_file, index=False)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "1c2cdefa", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "cc341889", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:55:25.347363Z", "iopub.status.busy": "2025-03-25T04:55:25.347263Z", "iopub.status.idle": "2025-03-25T04:55:25.373932Z", "shell.execute_reply": "2025-03-25T04:55:25.373571Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "First 20 gene/probe identifiers:\n", "Index(['10000_at', '10001_at', '10002_at', '100033413_at', '100033414_at',\n", " '100033416_at', '100033418_at', '100033420_at', '100033422_at',\n", " '100033423_at', '100033424_at', '100033425_at', '100033426_at',\n", " '100033427_at', '100033428_at', '100033430_at', '100033433_at',\n", " '100033434_at', '100033435_at', '100033436_at'],\n", " dtype='object', name='ID')\n", "\n", "Gene expression data shape: (19793, 8)\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": "c7f658e3", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "3e9cdf32", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:55:25.375225Z", "iopub.status.busy": "2025-03-25T04:55:25.375126Z", "iopub.status.idle": "2025-03-25T04:55:25.377070Z", "shell.execute_reply": "2025-03-25T04:55:25.376759Z" } }, "outputs": [], "source": [ "# The identifiers shown (like '2315554', '2315633', etc.) appear to be Illumina probe IDs \n", "# rather than standard human gene symbols. Human gene symbols would typically be alphanumeric\n", "# with recognizable patterns (like BRCA1, TP53, etc.).\n", "# \n", "# These numeric identifiers need to be mapped to standard gene symbols for meaningful biological interpretation.\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "61647a9d", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "127fdc02", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:55:25.378149Z", "iopub.status.busy": "2025-03-25T04:55:25.378052Z", "iopub.status.idle": "2025-03-25T04:55:29.543092Z", "shell.execute_reply": "2025-03-25T04:55:29.542692Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Sample of gene expression data (first 5 rows, first 5 columns):\n", " GSM684494 GSM684495 GSM684496 GSM684497 GSM684498\n", "ID \n", "10000_at 6.136420 6.145593 6.241496 6.000241 6.227926\n", "10001_at 7.314922 7.445762 7.431995 7.346254 7.388021\n", "10002_at 4.052602 4.070201 4.058046 4.246079 4.106251\n", "100033413_at 4.495692 4.831308 4.877297 4.173588 4.654585\n", "100033414_at 4.862921 4.545277 5.057613 5.010793 4.878975\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Platform information:\n", "!Series_title = A gene expression signature of emphysema-related lung destruction and its reversal by the tripeptide GHK.\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 = [HuGene10stv1_Hs_ENSG] Affymetrix GeneChip Human Gene 1.0 ST Array [Brainarray Version 11.0.1]\n", "!Platform_description = Probe set data extracted from custom CDF [Brainarray Version 11.0.1, HuGene10stv1_Hs_ENTREZG]\n", "!Platform_description =\n", "#Description =\n", "ID\tSPOT_ID\tDescription\n", "!Sample_description = RNA was treated for removal of ribosomal RNA, from which cDNA was synthesized, biotin-labeled, and hybridized to Human Exon 1.0 ST GeneChips. Transcript level data was obtained with RMA and the Affymetrix CDF using Expression Console Version 1.0 software.\n", "!Sample_description = RNA was treated for removal of ribosomal RNA, from which cDNA was synthesized, biotin-labeled, and hybridized to Human Exon 1.0 ST GeneChips. Transcript level data was obtained with RMA and the Affymetrix CDF using Expression Console Version 1.0 software.\n", "!Sample_description = RNA was treated for removal of ribosomal RNA, from which cDNA was synthesized, biotin-labeled, and hybridized to Human Exon 1.0 ST GeneChips. Transcript level data was obtained with RMA and the Affymetrix CDF using Expression Console Version 1.0 software.\n", "!Sample_description = RNA was treated for removal of ribosomal RNA, from which cDNA was synthesized, biotin-labeled, and hybridized to Human Exon 1.0 ST GeneChips. Transcript level data was obtained with RMA and the Affymetrix CDF using Expression Console Version 1.0 software.\n", "!Sample_description = RNA was treated for removal of ribosomal RNA, from which cDNA was synthesized, biotin-labeled, and hybridized to Human Exon 1.0 ST GeneChips. Transcript level data was obtained with RMA and the Affymetrix CDF using Expression Console Version 1.0 software.\n", "!Sample_description = RNA was treated for removal of ribosomal RNA, from which cDNA was synthesized, biotin-labeled, and hybridized to Human Exon 1.0 ST GeneChips. Transcript level data was obtained with RMA and the Affymetrix CDF using Expression Console Version 1.0 software.\n", "!Sample_description = RNA was treated for removal of ribosomal RNA, from which cDNA was synthesized, biotin-labeled, and hybridized to Human Exon 1.0 ST GeneChips. Transcript level data was obtained with RMA and the Affymetrix CDF using Expression Console Version 1.0 software.\n", "!Sample_description = RNA was treated for removal of ribosomal RNA, from which cDNA was synthesized, biotin-labeled, and hybridized to Human Exon 1.0 ST GeneChips. Transcript level data was obtained with RMA and the Affymetrix CDF using Expression Console Version 1.0 software.\n", "!Sample_description = RNA was treated for removal of ribosomal RNA, from which cDNA was synthesized, biotin-labeled, and hybridized to Human Exon 1.0 ST GeneChips. Transcript level data was obtained with RMA and the Affymetrix CDF using Expression Console Version 1.0 software.\n", "!Sample_description = RNA was treated for removal of ribosomal RNA, from which cDNA was synthesized, biotin-labeled, and hybridized to Human Exon 1.0 ST GeneChips. Transcript level data was obtained with RMA and the Affymetrix CDF using Expression Console Version 1.0 software.\n", "!Sample_description = RNA was treated for removal of ribosomal RNA, from which cDNA was synthesized, biotin-labeled, and hybridized to Human Exon 1.0 ST GeneChips. Transcript level data was obtained with RMA and the Affymetrix CDF using Expression Console Version 1.0 software.\n", "!Sample_description = RNA was treated for removal of ribosomal RNA, from which cDNA was synthesized, biotin-labeled, and hybridized to Human Exon 1.0 ST GeneChips. Transcript level data was obtained with RMA and the Affymetrix CDF using Expression Console Version 1.0 software.\n", "!Sample_description = RNA was treated for removal of ribosomal RNA, from which cDNA was synthesized, biotin-labeled, and hybridized to Human Exon 1.0 ST GeneChips. Transcript level data was obtained with RMA and the Affymetrix CDF using Expression Console Version 1.0 software.\n", "!Sample_description = RNA was treated for removal of ribosomal RNA, from which cDNA was synthesized, biotin-labeled, and hybridized to Human Exon 1.0 ST GeneChips. Transcript level data was obtained with RMA and the Affymetrix CDF using Expression Console Version 1.0 software.\n", "!Sample_description = RNA was treated for removal of ribosomal RNA, from which cDNA was synthesized, biotin-labeled, and hybridized to Human Exon 1.0 ST GeneChips. Transcript level data was obtained with RMA and the Affymetrix CDF using Expression Console Version 1.0 software.\n", "!Sample_description = RNA was treated for removal of ribosomal RNA, from which cDNA was synthesized, biotin-labeled, and hybridized to Human Exon 1.0 ST GeneChips. Transcript level data was obtained with RMA and the Affymetrix CDF using Expression Console Version 1.0 software.\n", "!Sample_description = RNA was treated for removal of ribosomal RNA, from which cDNA was synthesized, biotin-labeled, and hybridized to Human Exon 1.0 ST GeneChips. Transcript level data was obtained with RMA and the Affymetrix CDF using Expression Console Version 1.0 software.\n", "!Sample_description = RNA was treated for removal of ribosomal RNA, from which cDNA was synthesized, biotin-labeled, and hybridized to Human Exon 1.0 ST GeneChips. Transcript level data was obtained with RMA and the Affymetrix CDF using Expression Console Version 1.0 software.\n", "!Sample_description = RNA was treated for removal of ribosomal RNA, from which cDNA was synthesized, biotin-labeled, and hybridized to Human Exon 1.0 ST GeneChips. Transcript level data was obtained with RMA and the Affymetrix CDF using Expression Console Version 1.0 software.\n", "!Sample_description = RNA was treated for removal of ribosomal RNA, from which cDNA was synthesized, biotin-labeled, and hybridized to Human Exon 1.0 ST GeneChips. Transcript level data was obtained with RMA and the Affymetrix CDF using Expression Console Version 1.0 software.\n", "!Sample_description = RNA was treated for removal of ribosomal RNA, from which cDNA was synthesized, biotin-labeled, and hybridized to Human Exon 1.0 ST GeneChips. Transcript level data was obtained with RMA and the Affymetrix CDF using Expression Console Version 1.0 software.\n", "!Sample_description = RNA was treated for removal of ribosomal RNA, from which cDNA was synthesized, biotin-labeled, and hybridized to Human Exon 1.0 ST GeneChips. Transcript level data was obtained with RMA and the Affymetrix CDF using Expression Console Version 1.0 software.\n", "!Sample_description = RNA was treated for removal of ribosomal RNA, from which cDNA was synthesized, biotin-labeled, and hybridized to Human Exon 1.0 ST GeneChips. Transcript level data was obtained with RMA and the Affymetrix CDF using Expression Console Version 1.0 software.\n", "!Sample_description = RNA was treated for removal of ribosomal RNA, from which cDNA was synthesized, biotin-labeled, and hybridized to Human Exon 1.0 ST GeneChips. Transcript level data was obtained with RMA and the Affymetrix CDF using Expression Console Version 1.0 software.\n", "!Sample_description = RNA was treated for removal of ribosomal RNA, from which cDNA was synthesized, biotin-labeled, and hybridized to Human Exon 1.0 ST GeneChips. Transcript level data was obtained with RMA and the Affymetrix CDF using Expression Console Version 1.0 software.\n", "!Sample_description = RNA was treated for removal of ribosomal RNA, from which cDNA was synthesized, biotin-labeled, and hybridized to Human Exon 1.0 ST GeneChips. Transcript level data was obtained with RMA and the Affymetrix CDF using Expression Console Version 1.0 software.\n", "!Sample_description = RNA was treated for removal of ribosomal RNA, from which cDNA was synthesized, biotin-labeled, and hybridized to Human Exon 1.0 ST GeneChips. Transcript level data was obtained with RMA and the Affymetrix CDF using Expression Console Version 1.0 software.\n", "!Sample_description = RNA was treated for removal of ribosomal RNA, from which cDNA was synthesized, biotin-labeled, and hybridized to Human Exon 1.0 ST GeneChips. Transcript level data was obtained with RMA and the Affymetrix CDF using Expression Console Version 1.0 software.\n", "!Sample_description = RNA was treated for removal of ribosomal RNA, from which cDNA was synthesized, biotin-labeled, and hybridized to Human Exon 1.0 ST GeneChips. Transcript level data was obtained with RMA and the Affymetrix CDF using Expression Console Version 1.0 software.\n", "!Sample_description = RNA was treated for removal of ribosomal RNA, from which cDNA was synthesized, biotin-labeled, and hybridized to Human Exon 1.0 ST GeneChips. Transcript level data was obtained with RMA and the Affymetrix CDF using Expression Console Version 1.0 software.\n", "!Sample_description = RNA was treated for removal of ribosomal RNA, from which cDNA was synthesized, biotin-labeled, and hybridized to Human Exon 1.0 ST GeneChips. Transcript level data was obtained with RMA and the Affymetrix CDF using Expression Console Version 1.0 software.\n", "!Sample_description = RNA was treated for removal of ribosomal RNA, from which cDNA was synthesized, biotin-labeled, and hybridized to Human Exon 1.0 ST GeneChips. Transcript level data was obtained with RMA and the Affymetrix CDF using Expression Console Version 1.0 software.\n", "!Sample_description = RNA was treated for removal of ribosomal RNA, from which cDNA was synthesized, biotin-labeled, and hybridized to Human Exon 1.0 ST GeneChips. Transcript level data was obtained with RMA and the Affymetrix CDF using Expression Console Version 1.0 software.\n", "!Sample_description = RNA was treated for removal of ribosomal RNA, from which cDNA was synthesized, biotin-labeled, and hybridized to Human Exon 1.0 ST GeneChips. Transcript level data was obtained with RMA and the Affymetrix CDF using Expression Console Version 1.0 software.\n", "!Sample_description = RNA was treated for removal of ribosomal RNA, from which cDNA was synthesized, biotin-labeled, and hybridized to Human Exon 1.0 ST GeneChips. Transcript level data was obtained with RMA and the Affymetrix CDF using Expression Console Version 1.0 software.\n", "!Sample_description = RNA was treated for removal of ribosomal RNA, from which cDNA was synthesized, biotin-labeled, and hybridized to Human Exon 1.0 ST GeneChips. Transcript level data was obtained with RMA and the Affymetrix CDF using Expression Console Version 1.0 software.\n", "!Sample_description = RNA was treated for removal of ribosomal RNA, from which cDNA was synthesized, biotin-labeled, and hybridized to Human Exon 1.0 ST GeneChips. Transcript level data was obtained with RMA and the Affymetrix CDF using Expression Console Version 1.0 software.\n", "!Sample_description = RNA was treated for removal of ribosomal RNA, from which cDNA was synthesized, biotin-labeled, and hybridized to Human Exon 1.0 ST GeneChips. Transcript level data was obtained with RMA and the Affymetrix CDF using Expression Console Version 1.0 software.\n", "!Sample_description = RNA was treated for removal of ribosomal RNA, from which cDNA was synthesized, biotin-labeled, and hybridized to Human Exon 1.0 ST GeneChips. Transcript level data was obtained with RMA and the Affymetrix CDF using Expression Console Version 1.0 software.\n", "!Sample_description = RNA was treated for removal of ribosomal RNA, from which cDNA was synthesized, biotin-labeled, and hybridized to Human Exon 1.0 ST GeneChips. Transcript level data was obtained with RMA and the Affymetrix CDF using Expression Console Version 1.0 software.\n", "!Sample_description = RNA was treated for removal of ribosomal RNA, from which cDNA was synthesized, biotin-labeled, and hybridized to Human Exon 1.0 ST GeneChips. Transcript level data was obtained with RMA and the Affymetrix CDF using Expression Console Version 1.0 software.\n", "!Sample_description = RNA was treated for removal of ribosomal RNA, from which cDNA was synthesized, biotin-labeled, and hybridized to Human Exon 1.0 ST GeneChips. Transcript level data was obtained with RMA and the Affymetrix CDF using Expression Console Version 1.0 software.\n", "!Sample_description = RNA was treated for removal of ribosomal RNA, from which cDNA was synthesized, biotin-labeled, and hybridized to Human Exon 1.0 ST GeneChips. Transcript level data was obtained with RMA and the Affymetrix CDF using Expression Console Version 1.0 software.\n", "!Sample_description = RNA was treated for removal of ribosomal RNA, from which cDNA was synthesized, biotin-labeled, and hybridized to Human Exon 1.0 ST GeneChips. Transcript level data was obtained with RMA and the Affymetrix CDF using Expression Console Version 1.0 software.\n", "!Sample_description = RNA was treated for removal of ribosomal RNA, from which cDNA was synthesized, biotin-labeled, and hybridized to Human Exon 1.0 ST GeneChips. Transcript level data was obtained with RMA and the Affymetrix CDF using Expression Console Version 1.0 software.\n", "!Sample_description = RNA was treated for removal of ribosomal RNA, from which cDNA was synthesized, biotin-labeled, and hybridized to Human Exon 1.0 ST GeneChips. Transcript level data was obtained with RMA and the Affymetrix CDF using Expression Console Version 1.0 software.\n", "!Sample_description = RNA was treated for removal of ribosomal RNA, from which cDNA was synthesized, biotin-labeled, and hybridized to Human Exon 1.0 ST GeneChips. Transcript level data was obtained with RMA and the Affymetrix CDF using Expression Console Version 1.0 software.\n", "!Sample_description = RNA was treated for removal of ribosomal RNA, from which cDNA was synthesized, biotin-labeled, and hybridized to Human Exon 1.0 ST GeneChips. Transcript level data was obtained with RMA and the Affymetrix CDF using Expression Console Version 1.0 software.\n", "!Sample_description = RNA was treated for removal of ribosomal RNA, from which cDNA was synthesized, biotin-labeled, and hybridized to Human Exon 1.0 ST GeneChips. Transcript level data was obtained with RMA and the Affymetrix CDF using Expression Console Version 1.0 software.\n", "!Sample_description = RNA was treated for removal of ribosomal RNA, from which cDNA was synthesized, biotin-labeled, and hybridized to Human Exon 1.0 ST GeneChips. Transcript level data was obtained with RMA and the Affymetrix CDF using Expression Console Version 1.0 software.\n", "!Sample_description = RNA was treated for removal of ribosomal RNA, from which cDNA was synthesized, biotin-labeled, and hybridized to Human Exon 1.0 ST GeneChips. Transcript level data was obtained with RMA and the Affymetrix CDF using Expression Console Version 1.0 software.\n", "!Sample_description = RNA was treated for removal of ribosomal RNA, from which cDNA was synthesized, biotin-labeled, and hybridized to Human Exon 1.0 ST GeneChips. Transcript level data was obtained with RMA and the Affymetrix CDF using Expression Console Version 1.0 software.\n", "!Sample_description = RNA was treated for removal of ribosomal RNA, from which cDNA was synthesized, biotin-labeled, and hybridized to Human Exon 1.0 ST GeneChips. Transcript level data was obtained with RMA and the Affymetrix CDF using Expression Console Version 1.0 software.\n", "!Sample_description = RNA was treated for removal of ribosomal RNA, from which cDNA was synthesized, biotin-labeled, and hybridized to Human Exon 1.0 ST GeneChips. Transcript level data was obtained with RMA and the Affymetrix CDF using Expression Console Version 1.0 software.\n", "!Sample_description = RNA was treated for removal of ribosomal RNA, from which cDNA was synthesized, biotin-labeled, and hybridized to Human Exon 1.0 ST GeneChips. Transcript level data was obtained with RMA and the Affymetrix CDF using Expression Console Version 1.0 software.\n", "!Sample_description = RNA was treated for removal of ribosomal RNA, from which cDNA was synthesized, biotin-labeled, and hybridized to Human Exon 1.0 ST GeneChips. Transcript level data was obtained with RMA and the Affymetrix CDF using Expression Console Version 1.0 software.\n", "!Sample_description = RNA was treated for removal of ribosomal RNA, from which cDNA was synthesized, biotin-labeled, and hybridized to Human Exon 1.0 ST GeneChips. Transcript level data was obtained with RMA and the Affymetrix CDF using Expression Console Version 1.0 software.\n", "!Sample_description = RNA was treated for removal of ribosomal RNA, from which cDNA was synthesized, biotin-labeled, and hybridized to Human Exon 1.0 ST GeneChips. Transcript level data was obtained with RMA and the Affymetrix CDF using Expression Console Version 1.0 software.\n", "!Sample_description = RNA was treated for removal of ribosomal RNA, from which cDNA was synthesized, biotin-labeled, and hybridized to Human Exon 1.0 ST GeneChips. Transcript level data was obtained with RMA and the Affymetrix CDF using Expression Console Version 1.0 software.\n", "!Sample_description = RNA was treated for removal of ribosomal RNA, from which cDNA was synthesized, biotin-labeled, and hybridized to Human Exon 1.0 ST GeneChips. Transcript level data was obtained with RMA and the Affymetrix CDF using Expression Console Version 1.0 software.\n", "!Sample_description = RNA was treated for removal of ribosomal RNA, from which cDNA was synthesized, biotin-labeled, and hybridized to Human Exon 1.0 ST GeneChips. Transcript level data was obtained with RMA and the Affymetrix CDF using Expression Console Version 1.0 software.\n", "!Sample_description = RNA was treated for removal of ribosomal RNA, from which cDNA was synthesized, biotin-labeled, and hybridized to Human Exon 1.0 ST GeneChips. Transcript level data was obtained with RMA and the Affymetrix CDF using Expression Console Version 1.0 software.\n", "!Sample_description = RNA was treated for removal of ribosomal RNA, from which cDNA was synthesized, biotin-labeled, and hybridized to Human Exon 1.0 ST GeneChips. Transcript level data was obtained with RMA and the Affymetrix CDF using Expression Console Version 1.0 software.\n", "!Sample_description = RNA was treated for removal of ribosomal RNA, from which cDNA was synthesized, biotin-labeled, and hybridized to Human Exon 1.0 ST GeneChips. Transcript level data was obtained with RMA and the Affymetrix CDF using Expression Console Version 1.0 software.\n", "!Sample_description = High molecular weight RNA was isolated, converted to cDNA, biotin-labeled, and hybridized to Human Gene 1.0 ST GeneChips. Transcript-level gene expression estimates were generated via the robust multichip average (RMA) algorithm using the Entrez Gene CDF v11 (http://brainarray.mbni.med.umich.edu) in R v2.9.2.\n", "!Sample_description = High molecular weight RNA was isolated, converted to cDNA, biotin-labeled, and hybridized to Human Gene 1.0 ST GeneChips. Transcript-level gene expression estimates were generated via the robust multichip average (RMA) algorithm using the Entrez Gene CDF v11 (http://brainarray.mbni.med.umich.edu) in R v2.9.2.\n", "!Sample_description = High molecular weight RNA was isolated, converted to cDNA, biotin-labeled, and hybridized to Human Gene 1.0 ST GeneChips. Transcript-level gene expression estimates were generated via the robust multichip average (RMA) algorithm using the Entrez Gene CDF v11 (http://brainarray.mbni.med.umich.edu) in R v2.9.2.\n", "!Sample_description = High molecular weight RNA was isolated, converted to cDNA, biotin-labeled, and hybridized to Human Gene 1.0 ST GeneChips. Transcript-level gene expression estimates were generated via the robust multichip average (RMA) algorithm using the Entrez Gene CDF v11 (http://brainarray.mbni.med.umich.edu) in R v2.9.2.\n", "!Sample_description = High molecular weight RNA was isolated, converted to cDNA, biotin-labeled, and hybridized to Human Gene 1.0 ST GeneChips. Transcript-level gene expression estimates were generated via the robust multichip average (RMA) algorithm using the Entrez Gene CDF v11 (http://brainarray.mbni.med.umich.edu) in R v2.9.2.\n", "!Sample_description = High molecular weight RNA was isolated, converted to cDNA, biotin-labeled, and hybridized to Human Gene 1.0 ST GeneChips. Transcript-level gene expression estimates were generated via the robust multichip average (RMA) algorithm using the Entrez Gene CDF v11 (http://brainarray.mbni.med.umich.edu) in R v2.9.2.\n", "!Sample_description = High molecular weight RNA was isolated, converted to cDNA, biotin-labeled, and hybridized to Human Gene 1.0 ST GeneChips. Transcript-level gene expression estimates were generated via the robust multichip average (RMA) algorithm using the Entrez Gene CDF v11 (http://brainarray.mbni.med.umich.edu) in R v2.9.2.\n", "!Sample_description = High molecular weight RNA was isolated, converted to cDNA, biotin-labeled, and hybridized to Human Gene 1.0 ST GeneChips. Transcript-level gene expression estimates were generated via the robust multichip average (RMA) algorithm using the Entrez Gene CDF v11 (http://brainarray.mbni.med.umich.edu) in R v2.9.2.\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: 90\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": "e0acc915", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "a3e56b49", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:55:29.544383Z", "iopub.status.busy": "2025-03-25T04:55:29.544265Z", "iopub.status.idle": "2025-03-25T04:55:29.835342Z", "shell.execute_reply": "2025-03-25T04:55:29.834979Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Sample IDs from gene expression data:\n", "Index(['10000_at', '10001_at', '10002_at', '100033413_at', '100033414_at'], dtype='object', name='ID')\n", "Number of matching IDs between expression data and annotation: 19793\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Sample of the gene mapping dataframe:\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", "Shape of mapping dataframe: (316481, 2)\n", "\n", "Resulting gene expression dataframe:\n", "Shape: (0, 8)\n", "First few gene symbols:\n", "Index([], dtype='object', name='Gene')\n", "\n", "Normalized gene expression dataframe:\n", "Shape: (0, 8)\n", "First few normalized gene symbols:\n", "Index([], dtype='object', name='Gene')\n", "\n", "Gene expression data saved to ../../output/preprocess/Von_Willebrand_Disease/gene_data/GSE27597.csv\n" ] } ], "source": [ "# 1. Based on the annotation preview, we need to identify the correct mapping columns\n", "# Examining the fields, we see:\n", "# - 'ID' column in the annotation looks like it contains the same probe identifiers (like '2315100')\n", "# that are indexed in the gene expression data\n", "# - 'gene_assignment' column appears to contain gene symbol information\n", "\n", "# Examine a sample of IDs from gene expression data to confirm\n", "print(\"Sample IDs from gene expression data:\")\n", "print(gene_data.index[:5])\n", "\n", "# Let's verify if these IDs match those in the annotation dataframe\n", "matching_ids = set(gene_data.index) & set(gene_annotation['ID'])\n", "print(f\"Number of matching IDs between expression data and annotation: {len(matching_ids)}\")\n", "\n", "# 2. Create gene mapping dataframe\n", "# The 'gene_assignment' column contains gene symbols, but in a complex format\n", "# We need to extract gene symbols from this format using the library function\n", "prob_col = 'ID'\n", "gene_col = 'gene_assignment'\n", "mapping_df = get_gene_mapping(gene_annotation, prob_col, gene_col)\n", "\n", "# Display a sample of the mapping data to verify\n", "print(\"\\nSample of the gene mapping dataframe:\")\n", "print(mapping_df.head())\n", "print(f\"Shape of mapping dataframe: {mapping_df.shape}\")\n", "\n", "# 3. Apply gene mapping to convert probe-level measurements to gene-level expression\n", "gene_expression_df = apply_gene_mapping(gene_data, mapping_df)\n", "\n", "# Print information about the resulting gene expression dataframe\n", "print(\"\\nResulting gene expression dataframe:\")\n", "print(f\"Shape: {gene_expression_df.shape}\")\n", "print(\"First few gene symbols:\")\n", "print(gene_expression_df.index[:10])\n", "\n", "# Normalize gene symbols using NCBI Gene database information\n", "gene_data = normalize_gene_symbols_in_index(gene_expression_df)\n", "\n", "# Print information about the normalized gene expression dataframe\n", "print(\"\\nNormalized gene expression dataframe:\")\n", "print(f\"Shape: {gene_data.shape}\")\n", "print(\"First few normalized gene symbols:\")\n", "print(gene_data.index[:10])\n", "\n", "# Save the gene expression data to a file\n", "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", "gene_data.to_csv(out_gene_data_file)\n", "print(f\"\\nGene expression data saved to {out_gene_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "1320a0b1", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "85e10a9f", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:55:29.836694Z", "iopub.status.busy": "2025-03-25T04:55:29.836585Z", "iopub.status.idle": "2025-03-25T04:55:29.905387Z", "shell.execute_reply": "2025-03-25T04:55:29.905016Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape after normalization: (0, 8)\n", "First few gene symbols after normalization: []\n", "Normalized gene data saved to ../../output/preprocess/Von_Willebrand_Disease/gene_data/GSE27597.csv\n", "Loaded clinical data:\n", " 1 2\n", "0 \n", "0.0 0.0 0.0\n", "NaN NaN NaN\n", "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: [0.0, nan, nan]\n", "Gene data columns: ['GSM684494', 'GSM684495', 'GSM684496', 'GSM684497', 'GSM684498', '...']\n", "Extracted 8 GSM IDs from gene data.\n", "Created new clinical data with matching sample IDs:\n", " Von_Willebrand_Disease\n", "GSM684494 1\n", "GSM684495 1\n", "GSM684496 1\n", "GSM684497 1\n", "GSM684498 1\n", "Gene data shape for linking (samples as rows): (8, 0)\n", "Linked data shape: (8, 1)\n", "Linked data preview (first 5 columns):\n", " Von_Willebrand_Disease\n", "GSM684494 1\n", "GSM684495 1\n", "GSM684496 1\n", "GSM684497 1\n", "GSM684498 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: GSE27597. Preprocessing failed.\n", "A new JSON file was created at: ../../output/preprocess/Von_Willebrand_Disease/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 }