{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "68ed475f", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:43:11.668559Z", "iopub.status.busy": "2025-03-25T08:43:11.668440Z", "iopub.status.idle": "2025-03-25T08:43:11.835036Z", "shell.execute_reply": "2025-03-25T08:43:11.834646Z" } }, "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 = \"Endometrioid_Cancer\"\n", "cohort = \"GSE94523\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Endometrioid_Cancer\"\n", "in_cohort_dir = \"../../input/GEO/Endometrioid_Cancer/GSE94523\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Endometrioid_Cancer/GSE94523.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Endometrioid_Cancer/gene_data/GSE94523.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Endometrioid_Cancer/clinical_data/GSE94523.csv\"\n", "json_path = \"../../output/preprocess/Endometrioid_Cancer/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "19cbfb6a", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "281e6101", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:43:11.836533Z", "iopub.status.busy": "2025-03-25T08:43:11.836384Z", "iopub.status.idle": "2025-03-25T08:43:12.024282Z", "shell.execute_reply": "2025-03-25T08:43:12.023928Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Tamoxifen-associated endometrial tumors expose differential enhancer activity for Estrogen Receptor alpha [Microarray Expression]\"\n", "!Series_summary\t\"Tamoxifen, a small molecule inhibitor that binds the Estrogen Receptor alpha (ERα), blocks breast cancer progression while increasing the risk for endometrial cancer. In this study, we assessed genome-wide ERα-chromatin interactions in surgical specimens of endometrial tumors from patients who were previously treated for breast cancer with tamoxifen, and endometrial tumors from patients who were treated without tamoxifen. We compared ERα and signal at differential ERα sites in endometrial tumors of nine patients who received tamoxifen with endometrial tumors with six patients who never used tamoxifen. In addition, we performed H3K27ac (a marker for activity) ChIPs on the above mentioned endometrial tumors, and assed this signal at differential ERα sites. Compared to endometrial tumors of non-users, tamoxifen-associated endometrial tumors exposed higher H3K27ac intensities at ERα sites that are enriched in tamoxifen-associated endometrial tumors. Four tamoxifen-associated endometrial tumors that we used in our analysis have been previously published as Tumor A, B, D, and E in GSE81213.\"\n", "!Series_overall_design\t\"Gene expression profiling in 111 endometrial tumors\"\n", "Sample Characteristics Dictionary:\n", "{0: ['tissue: endometrioid adenocarcinoma']}\n" ] } ], "source": [ "from tools.preprocess import *\n", "# 1. Identify the paths to the SOFT file and the matrix file\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# 2. Read the matrix file to obtain background information and sample characteristics data\n", "background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']\n", "clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']\n", "background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n", "\n", "# 3. Obtain the sample characteristics dictionary from the clinical dataframe\n", "sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n", "\n", "# 4. Explicitly print out all the background information and the sample characteristics dictionary\n", "print(\"Background Information:\")\n", "print(background_info)\n", "print(\"Sample Characteristics Dictionary:\")\n", "print(sample_characteristics_dict)\n" ] }, { "cell_type": "markdown", "id": "0e29d2a4", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "d499e45b", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:43:12.025642Z", "iopub.status.busy": "2025-03-25T08:43:12.025515Z", "iopub.status.idle": "2025-03-25T08:43:12.031814Z", "shell.execute_reply": "2025-03-25T08:43:12.031476Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Clinical features preview: {0: [1.0]}\n", "Clinical features saved to ../../output/preprocess/Endometrioid_Cancer/clinical_data/GSE94523.csv\n" ] } ], "source": [ "import pandas as pd\n", "import os\n", "import json\n", "from typing import Callable, Optional, Dict, Any\n", "\n", "# Analyze the dataset for gene expression data\n", "# Based on the background information, this appears to be microarray expression data for endometrial tumors\n", "is_gene_available = True\n", "\n", "# Analyze for trait data availability\n", "# From the sample characteristics, we can see all samples are 'endometrioid adenocarcinoma' \n", "trait_row = 0 # The key in the sample characteristics where the trait information is stored\n", "\n", "# Check for age data\n", "# No age information is provided in the sample characteristics\n", "age_row = None\n", "\n", "# Check for gender data\n", "# This is endometrial cancer which occurs only in females, so gender would be constant\n", "gender_row = None\n", "\n", "# Define conversion function for trait\n", "def convert_trait(value):\n", " # Extract the actual value after the colon\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Since we're studying Endometrioid_Cancer, and all samples are endometrioid adenocarcinoma\n", " # we'll use binary classification: 1 for having the condition\n", " return 1\n", "\n", "# Age conversion function (not used, but defined for completeness)\n", "def convert_age(value):\n", " return None\n", "\n", "# Gender conversion function (not used, but defined for completeness)\n", "def convert_gender(value):\n", " return None\n", "\n", "# Validate and save cohort info\n", "is_trait_available = trait_row is not None\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", "# If trait data is available, extract clinical features\n", "if trait_row is not None:\n", " # Load clinical data (assuming it was obtained in a previous step)\n", " # Using the sample characteristics dictionary from the previous step\n", " clinical_data = pd.DataFrame({0: ['tissue: endometrioid adenocarcinoma']})\n", " \n", " # Extract clinical features\n", " clinical_features = 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 extracted features\n", " preview = preview_df(clinical_features)\n", " print(\"Clinical features preview:\", preview)\n", " \n", " # Create output directory if it doesn't exist\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " \n", " # Save clinical features to CSV\n", " clinical_features.to_csv(out_clinical_data_file)\n", " print(f\"Clinical features saved to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "0748df14", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "c475ca57", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:43:12.033023Z", "iopub.status.busy": "2025-03-25T08:43:12.032901Z", "iopub.status.idle": "2025-03-25T08:43:12.417906Z", "shell.execute_reply": "2025-03-25T08:43:12.417509Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Found data marker at line 74\n", "Header line: \"ID_REF\"\t\"GSM2477471\"\t\"GSM2477472\"\t\"GSM2477473\"\t\"GSM2477474\"\t\"GSM2477475\"\t\"GSM2477476\"\t\"GSM2477477\"\t\"GSM2477478\"\t\"GSM2477479\"\t\"GSM2477480\"\t\"GSM2477481\"\t\"GSM2477482\"\t\"GSM2477483\"\t\"GSM2477484\"\t\"GSM2477485\"\t\"GSM2477486\"\t\"GSM2477487\"\t\"GSM2477488\"\t\"GSM2477489\"\t\"GSM2477490\"\t\"GSM2477491\"\t\"GSM2477492\"\t\"GSM2477493\"\t\"GSM2477494\"\t\"GSM2477495\"\t\"GSM2477496\"\t\"GSM2477497\"\t\"GSM2477498\"\t\"GSM2477499\"\t\"GSM2477500\"\t\"GSM2477501\"\t\"GSM2477502\"\t\"GSM2477503\"\t\"GSM2477504\"\t\"GSM2477505\"\t\"GSM2477506\"\t\"GSM2477507\"\t\"GSM2477508\"\t\"GSM2477509\"\t\"GSM2477510\"\t\"GSM2477511\"\t\"GSM2477512\"\t\"GSM2477513\"\t\"GSM2477514\"\t\"GSM2477515\"\t\"GSM2477516\"\t\"GSM2477517\"\t\"GSM2477518\"\t\"GSM2477519\"\t\"GSM2477520\"\t\"GSM2477521\"\t\"GSM2477522\"\t\"GSM2477523\"\t\"GSM2477524\"\t\"GSM2477525\"\t\"GSM2477526\"\t\"GSM2477527\"\t\"GSM2477528\"\t\"GSM2477529\"\t\"GSM2477530\"\t\"GSM2477531\"\t\"GSM2477532\"\t\"GSM2477533\"\t\"GSM2477534\"\t\"GSM2477535\"\t\"GSM2477536\"\t\"GSM2477537\"\t\"GSM2477538\"\t\"GSM2477539\"\t\"GSM2477540\"\t\"GSM2477541\"\t\"GSM2477542\"\t\"GSM2477543\"\t\"GSM2477544\"\t\"GSM2477545\"\t\"GSM2477546\"\t\"GSM2477547\"\t\"GSM2477548\"\t\"GSM2477549\"\t\"GSM2477550\"\t\"GSM2477551\"\t\"GSM2477552\"\t\"GSM2477553\"\t\"GSM2477554\"\t\"GSM2477555\"\t\"GSM2477556\"\t\"GSM2477557\"\t\"GSM2477558\"\t\"GSM2477559\"\t\"GSM2477560\"\t\"GSM2477561\"\t\"GSM2477562\"\t\"GSM2477563\"\t\"GSM2477564\"\t\"GSM2477565\"\t\"GSM2477566\"\t\"GSM2477567\"\t\"GSM2477568\"\t\"GSM2477569\"\t\"GSM2477570\"\t\"GSM2477571\"\t\"GSM2477572\"\t\"GSM2477573\"\t\"GSM2477574\"\t\"GSM2477575\"\t\"GSM2477576\"\t\"GSM2477577\"\t\"GSM2477578\"\t\"GSM2477579\"\t\"GSM2477580\"\t\"GSM2477581\"\n", "First data line: 1\t-0.0971308\t-0.721129\t-0.200969\t0.248083\t0.13323\t1.05233\t-0.751642\t0.171953\t0.161565\t-0.569857\t-0.520999\t-0.416249\t0.497888\t0.394718\t0.0659212\t0.678106\t-0.308858\t-0.513857\t0.519296\t0.941124\t0.294259\t0.604991\t0.273212\t1.34738\t0.142156\t0.201991\t0.283873\t1.07171\t-0.512929\t0.497443\t-0.418567\t-0.133336\t-0.209668\t-0.370017\t-0.256996\t-0.815727\t-0.680033\t-0.295943\t0.0412299\t-0.197013\t0.275417\t1.7749\t0.248064\t-0.00444559\t-0.128249\t-0.733087\t-1.04673\t-1.01148\t-0.204086\t-0.372505\t-0.363915\t-0.885154\t-0.292058\t-0.132823\t-0.385885\t-0.22107\t-0.5878\t0.356115\t0.224173\t2.90244\t2.30603\t-1.02894\t-0.892737\t0.120025\t-0.534206\t0.393176\t-0.267239\t0.261731\t-0.394545\t-0.00729317\t-0.431308\t-1.13973\t-0.187582\t0.693875\t-0.851932\t-0.565655\t-0.451916\t-0.649568\t-0.680746\t-0.762242\t-0.0869032\t-0.658805\t-0.871096\t0.138606\t-1.72013\t-1.12094\t0.885628\t-0.0268155\t0.678802\t-0.54545\t-0.558044\t-0.301035\t-0.116336\t-0.179637\t-0.662978\t-0.595398\t-0.146877\t-0.640617\t-0.534543\t-0.19727\t0.869927\t-0.420415\t0.757306\t0.559833\t-0.0654352\t0.130097\t-0.376034\t0.178725\t0.0695361\t-0.458078\t-0.439257\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "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" ] } ], "source": [ "# 1. Get the file paths for the SOFT file and matrix file\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# 2. First, let's examine the structure of the matrix file to understand its format\n", "import gzip\n", "\n", "# Peek at the first few lines of the file to understand its structure\n", "with gzip.open(matrix_file, 'rt') as file:\n", " # Read first 100 lines to find the header structure\n", " for i, line in enumerate(file):\n", " if '!series_matrix_table_begin' in line:\n", " print(f\"Found data marker at line {i}\")\n", " # Read the next line which should be the header\n", " header_line = next(file)\n", " print(f\"Header line: {header_line.strip()}\")\n", " # And the first data line\n", " first_data_line = next(file)\n", " print(f\"First data line: {first_data_line.strip()}\")\n", " break\n", " if i > 100: # Limit search to first 100 lines\n", " print(\"Matrix table marker not found in first 100 lines\")\n", " break\n", "\n", "# 3. Now try to get the genetic data with better error handling\n", "try:\n", " gene_data = get_genetic_data(matrix_file)\n", " print(gene_data.index[:20])\n", "except KeyError as e:\n", " print(f\"KeyError: {e}\")\n", " \n", " # Alternative approach: manually extract the data\n", " print(\"\\nTrying alternative approach to read the gene data:\")\n", " with gzip.open(matrix_file, 'rt') as file:\n", " # Find the start of the data\n", " for line in file:\n", " if '!series_matrix_table_begin' in line:\n", " break\n", " \n", " # Read the headers and data\n", " import pandas as pd\n", " df = pd.read_csv(file, sep='\\t', index_col=0)\n", " print(f\"Column names: {df.columns[:5]}\")\n", " print(f\"First 20 row IDs: {df.index[:20]}\")\n", " gene_data = df\n" ] }, { "cell_type": "markdown", "id": "3d24b379", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "2d701739", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:43:12.419383Z", "iopub.status.busy": "2025-03-25T08:43:12.419251Z", "iopub.status.idle": "2025-03-25T08:43:12.421320Z", "shell.execute_reply": "2025-03-25T08:43:12.420973Z" } }, "outputs": [], "source": [ "# Looking at the gene identifiers, I can see they are numeric (1, 2, 3...) rather than\n", "# human gene symbols like BRCA1, TP53, etc.\n", "# These appear to be probe IDs or feature indices, not actual gene symbols.\n", "# Therefore, we will need to map these identifiers to proper gene symbols.\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "cb66a40a", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "015b606e", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:43:12.422602Z", "iopub.status.busy": "2025-03-25T08:43:12.422489Z", "iopub.status.idle": "2025-03-25T08:43:20.024062Z", "shell.execute_reply": "2025-03-25T08:43:20.023609Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene annotation preview:\n", "{'ID': ['1', '2', '3', '4', '5'], 'MetaRow': ['12', '12', '12', '12', '12'], 'MetaCol': ['4', '4', '4', '4', '4'], 'SubRow': ['28', '27', '26', '25', '24'], 'SubCol': [28.0, 28.0, 28.0, 28.0, 28.0], 'Reporter ID': [334575.0, 333055.0, 331915.0, 330395.0, 328875.0], 'oligo_id': ['H300009761', 'H300009722', 'H300000470', 'H300000646', 'H300004276'], 'oligo_type': ['I', 'I', 'I', 'I', 'I'], 'gene_id': ['ENSG00000182037', 'ENSG00000180563', 'ENSG00000179449', 'ENSG00000177996', 'ENSG00000176539'], 'transcript_count': [1.0, 1.0, 1.0, 1.0, 1.0], 'representative_transcript_id': ['ENST00000315389', 'ENST00000316343', 'ENST00000314233', 'ENST00000325950', 'ENST00000326170'], 'HUGO': [nan, nan, 'MAGEL2', nan, nan], 'GB_LIST': [nan, nan, 'NM_019066, AF200625', nan, nan], 'GI-Bacillus': [nan, nan, nan, nan, nan], 'SPOT_ID': ['ENSG00000182037', 'ENSG00000180563', nan, 'ENSG00000177996', 'ENSG00000176539'], 'SEQUENCE': ['TTAATCTGACCTGTGAAAAACACTGTCCAGAGGCTAGGTGCGGTGGCTAACGCTTGTAATCCCAGCACTT', 'TGTTGCTGACTCGAAGTCTGAAGGAAAGTTCGATGGTGCAAAAGTTAAAGTTGCCTGGAAAAAGGTAGAC', 'AAGCTGGGCTACCATACAGGGAATTTGGTGGCATCCTATTTAGACAGGCCCAAGTTTGGCCTTCTGATGG', 'AATGCAGAAGCCTCAGGAGCCGATGCAATCAACTGGAAGAAAAGGTATCAGCAATGGAAGATGAAATGAA', 'CGCGGCACCAACCCTCAATATCTGGTGGGGAAGATCATTCGAATGCGAATCTGTGAGTCCAAGCACTGGA']}\n" ] } ], "source": [ "# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n", "gene_annotation = get_gene_annotation(soft_file)\n", "\n", "# 2. Use the 'preview_df' function from the library to preview the data and print out the results.\n", "print(\"Gene annotation preview:\")\n", "print(preview_df(gene_annotation))\n" ] }, { "cell_type": "markdown", "id": "9d9a985b", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "bbf6d1ff", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:43:20.025348Z", "iopub.status.busy": "2025-03-25T08:43:20.025220Z", "iopub.status.idle": "2025-03-25T08:43:42.774878Z", "shell.execute_reply": "2025-03-25T08:43:42.774234Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Percentage of rows with HUGO gene symbols: 0.35%\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Mapping dataframe shape: (34547, 2)\n", "Sample of mapping dataframe:\n", " ID Gene\n", "0 1 ENSG00000182037\n", "1 2 ENSG00000180563\n", "2 3 MAGEL2\n", "3 4 ENSG00000177996\n", "4 5 ENSG00000176539\n", "Gene expression data shape after mapping: (19986, 111)\n", "First few gene symbols after mapping:\n", "['A1BG', 'A2M', 'A4GALT', 'AAAS', 'AADAC']\n" ] } ], "source": [ "# 1. Identify the appropriate columns for mapping\n", "# The 'ID' column contains the identifiers matching the gene expression data\n", "# For gene symbols, 'HUGO' contains some gene symbols, but has many NaN values\n", "# We'll need to use a combination of identifiers\n", "\n", "# 2. Create a mapping dataframe that maps probe IDs to gene symbols\n", "# First, let's examine what percentage of entries have HUGO symbols\n", "print(f\"Percentage of rows with HUGO gene symbols: {gene_annotation['HUGO'].notna().mean()*100:.2f}%\")\n", "\n", "# Let's create a function to extract the best available gene symbol for each row\n", "def get_best_gene_symbol(row):\n", " # First preference: HUGO gene symbol if available\n", " if pd.notna(row['HUGO']):\n", " return row['HUGO']\n", " # Second preference: Extract symbols from GB_LIST if available\n", " elif pd.notna(row['GB_LIST']):\n", " # Try to extract symbols from GB_LIST using the gene extraction function\n", " symbols = extract_human_gene_symbols(row['GB_LIST'])\n", " if symbols:\n", " return symbols[0] # Return the first symbol if any found\n", " # Third preference: Use Ensembl gene ID if available (will be normalized later)\n", " elif pd.notna(row['gene_id']):\n", " return row['gene_id']\n", " # If nothing else is available\n", " return None\n", "\n", "# Apply the function to create a new column with the best available gene symbol\n", "gene_annotation['Gene'] = gene_annotation.apply(get_best_gene_symbol, axis=1)\n", "\n", "# Create the mapping dataframe with probe IDs and gene symbols\n", "mapping_df = gene_annotation[['ID', 'Gene']].dropna()\n", "print(f\"Mapping dataframe shape: {mapping_df.shape}\")\n", "print(f\"Sample of mapping dataframe:\")\n", "print(mapping_df.head())\n", "\n", "# 3. Apply the gene mapping to convert probe-level measurements to gene expression data\n", "gene_data = apply_gene_mapping(gene_data, mapping_df)\n", "\n", "# Preview the resulting gene expression data\n", "print(f\"Gene expression data shape after mapping: {gene_data.shape}\")\n", "print(f\"First few gene symbols after mapping:\")\n", "print(list(gene_data.index[:5]))\n" ] }, { "cell_type": "markdown", "id": "7db075f5", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "b647cf16", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:43:42.776747Z", "iopub.status.busy": "2025-03-25T08:43:42.776620Z", "iopub.status.idle": "2025-03-25T08:43:45.605668Z", "shell.execute_reply": "2025-03-25T08:43:45.605197Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data shape: (9628, 111)\n", "First few genes with their expression values after normalization:\n", " GSM2477471 GSM2477472 GSM2477473 GSM2477474 GSM2477475 \\\n", "Gene \n", "A1BG 0.152441 -0.328190 -0.402093 -0.459311 -0.044677 \n", "A2M 0.194438 -1.377660 -0.561084 1.047960 0.589405 \n", "A4GALT 1.089600 0.343792 0.053120 0.364721 0.088068 \n", "AAAS -0.532202 0.709348 -0.419568 0.101501 -0.501564 \n", "AADAC 0.282887 -1.911730 0.000000 3.241060 0.711206 \n", "\n", " GSM2477476 GSM2477477 GSM2477478 GSM2477479 GSM2477480 ... \\\n", "Gene ... \n", "A1BG 0.990185 0.305397 0.038350 -0.176839 -0.323575 ... \n", "A2M -1.436880 -0.413543 -0.884551 0.254121 0.984051 ... \n", "A4GALT -0.122575 0.008176 0.927995 -0.029103 0.440727 ... \n", "AAAS -0.374575 -0.298828 -0.494604 0.080157 0.290037 ... \n", "AADAC 0.608551 -0.038366 0.107336 -0.018521 0.159903 ... \n", "\n", " GSM2477572 GSM2477573 GSM2477574 GSM2477575 GSM2477576 \\\n", "Gene \n", "A1BG -0.110421 0.597255 -0.069516 -0.048005 -0.072845 \n", "A2M -0.259256 -0.631996 -0.591483 -1.450280 -0.300649 \n", "A4GALT 0.226608 0.932822 0.090341 -0.265511 0.369433 \n", "AAAS 0.648848 -1.026081 -0.001133 -0.025974 0.771225 \n", "AADAC 0.196259 -1.002740 -0.493535 0.786658 0.584659 \n", "\n", " GSM2477577 GSM2477578 GSM2477579 GSM2477580 GSM2477581 \n", "Gene \n", "A1BG -0.355872 -0.030880 0.029083 0.168261 -0.198460 \n", "A2M 0.254731 -0.229838 0.735989 -0.031862 0.285643 \n", "A4GALT 0.915050 0.630422 0.351745 0.121407 0.875033 \n", "AAAS 0.033049 0.165428 0.429637 -0.398371 0.693071 \n", "AADAC -0.423969 0.000000 0.036809 -0.530891 0.000000 \n", "\n", "[5 rows x 111 columns]\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data saved to ../../output/preprocess/Endometrioid_Cancer/gene_data/GSE94523.csv\n", "Raw clinical data shape: (1, 112)\n", "Clinical features:\n", " GSM2477471 GSM2477472 GSM2477473 GSM2477474 \\\n", "Endometrioid_Cancer 1.0 1.0 1.0 1.0 \n", "\n", " GSM2477475 GSM2477476 GSM2477477 GSM2477478 \\\n", "Endometrioid_Cancer 1.0 1.0 1.0 1.0 \n", "\n", " GSM2477479 GSM2477480 ... GSM2477572 GSM2477573 \\\n", "Endometrioid_Cancer 1.0 1.0 ... 1.0 1.0 \n", "\n", " GSM2477574 GSM2477575 GSM2477576 GSM2477577 \\\n", "Endometrioid_Cancer 1.0 1.0 1.0 1.0 \n", "\n", " GSM2477578 GSM2477579 GSM2477580 GSM2477581 \n", "Endometrioid_Cancer 1.0 1.0 1.0 1.0 \n", "\n", "[1 rows x 111 columns]\n", "Clinical features saved to ../../output/preprocess/Endometrioid_Cancer/clinical_data/GSE94523.csv\n", "Linked data shape: (111, 9629)\n", "Linked data preview (first 5 rows, first 5 columns):\n", " Endometrioid_Cancer A1BG A2M A4GALT AAAS\n", "GSM2477471 1.0 0.152441 0.194438 1.089600 -0.532202\n", "GSM2477472 1.0 -0.328190 -1.377660 0.343792 0.709348\n", "GSM2477473 1.0 -0.402093 -0.561084 0.053120 -0.419568\n", "GSM2477474 1.0 -0.459311 1.047960 0.364721 0.101501\n", "GSM2477475 1.0 -0.044677 0.589405 0.088068 -0.501564\n", "Missing values before handling:\n", " Trait (Endometrioid_Cancer) missing: 0 out of 111\n", " Genes with >20% missing: 0\n", " Samples with >5% missing genes: 0\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Data shape after handling missing values: (111, 9629)\n", "Quartiles for 'Endometrioid_Cancer':\n", " 25%: 1.0\n", " 50% (Median): 1.0\n", " 75%: 1.0\n", "Min: 1.0\n", "Max: 1.0\n", "The distribution of the feature 'Endometrioid_Cancer' in this dataset is severely biased.\n", "\n", "Data was determined to be unusable or empty and was not saved\n" ] } ], "source": [ "# 1. Normalize gene symbols in the gene expression data\n", "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"Normalized gene data shape: {normalized_gene_data.shape}\")\n", "print(\"First few genes with their expression values after normalization:\")\n", "print(normalized_gene_data.head())\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", "\n", "# 2. Check if trait data is available before proceeding with clinical data extraction\n", "if trait_row is None:\n", " print(\"Trait row is None. Cannot extract trait information from clinical data.\")\n", " # Create an empty dataframe for clinical features\n", " clinical_features = pd.DataFrame()\n", " \n", " # Create an empty dataframe for linked data\n", " linked_data = pd.DataFrame()\n", " \n", " # Validate and save cohort info\n", " validate_and_save_cohort_info(\n", " is_final=True, \n", " cohort=cohort, \n", " info_path=json_path, \n", " is_gene_available=True, \n", " is_trait_available=False, # Trait data is not available\n", " is_biased=True, # Not applicable but required\n", " df=pd.DataFrame(), # Empty dataframe\n", " note=\"Dataset contains gene expression data but lacks clear trait indicators for Duchenne Muscular Dystrophy status.\"\n", " )\n", " print(\"Data was determined to be unusable due to missing trait indicators and was not saved\")\n", "else:\n", " try:\n", " # Get the file paths for the matrix file to extract clinical data\n", " _, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", " \n", " # Get raw clinical data from the matrix file\n", " _, clinical_raw = get_background_and_clinical_data(matrix_file)\n", " \n", " # Verify clinical data structure\n", " print(\"Raw clinical data shape:\", clinical_raw.shape)\n", " \n", " # Extract clinical features using the defined conversion functions\n", " clinical_features = geo_select_clinical_features(\n", " clinical_df=clinical_raw,\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", " print(\"Clinical features:\")\n", " print(clinical_features)\n", " \n", " # Save clinical features to file\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " clinical_features.to_csv(out_clinical_data_file)\n", " print(f\"Clinical features saved to {out_clinical_data_file}\")\n", " \n", " # 3. Link clinical and genetic data\n", " linked_data = geo_link_clinical_genetic_data(clinical_features, normalized_gene_data)\n", " print(f\"Linked data shape: {linked_data.shape}\")\n", " print(\"Linked data preview (first 5 rows, first 5 columns):\")\n", " print(linked_data.iloc[:5, :5])\n", " \n", " # 4. Handle missing values\n", " print(\"Missing values before handling:\")\n", " print(f\" Trait ({trait}) missing: {linked_data[trait].isna().sum()} out of {len(linked_data)}\")\n", " if 'Age' in linked_data.columns:\n", " print(f\" Age missing: {linked_data['Age'].isna().sum()} out of {len(linked_data)}\")\n", " if 'Gender' in linked_data.columns:\n", " print(f\" Gender missing: {linked_data['Gender'].isna().sum()} out of {len(linked_data)}\")\n", " \n", " gene_cols = [col for col in linked_data.columns if col not in [trait, 'Age', 'Gender']]\n", " print(f\" Genes with >20% missing: {sum(linked_data[gene_cols].isna().mean() > 0.2)}\")\n", " print(f\" Samples with >5% missing genes: {sum(linked_data[gene_cols].isna().mean(axis=1) > 0.05)}\")\n", " \n", " cleaned_data = handle_missing_values(linked_data, trait)\n", " print(f\"Data shape after handling missing values: {cleaned_data.shape}\")\n", " \n", " # 5. Evaluate bias in trait and demographic features\n", " is_trait_biased = False\n", " if len(cleaned_data) > 0:\n", " trait_biased, cleaned_data = judge_and_remove_biased_features(cleaned_data, trait)\n", " is_trait_biased = trait_biased\n", " else:\n", " print(\"No data remains after handling missing values.\")\n", " is_trait_biased = True\n", " \n", " # 6. Final validation and save\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=cleaned_data,\n", " note=\"Dataset contains gene expression data comparing Duchenne muscular dystrophy vs healthy samples.\"\n", " )\n", " \n", " # 7. Save if usable\n", " if is_usable and len(cleaned_data) > 0:\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " cleaned_data.to_csv(out_data_file)\n", " print(f\"Linked data saved to {out_data_file}\")\n", " else:\n", " print(\"Data was determined to be unusable or empty and was not saved\")\n", " \n", " except Exception as e:\n", " print(f\"Error processing data: {e}\")\n", " # Handle the error case by still recording cohort info\n", " validate_and_save_cohort_info(\n", " is_final=True, \n", " cohort=cohort, \n", " info_path=json_path, \n", " is_gene_available=True, \n", " is_trait_available=False, # Mark as not available due to processing issues\n", " is_biased=True, \n", " df=pd.DataFrame(), # Empty dataframe\n", " note=f\"Error processing data: {str(e)}\"\n", " )\n", " print(\"Data was determined to be unusable and was not saved\")" ] } ], "metadata": { "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.16" } }, "nbformat": 4, "nbformat_minor": 5 }