{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "d004f651", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:43:46.454302Z", "iopub.status.busy": "2025-03-25T08:43:46.454159Z", "iopub.status.idle": "2025-03-25T08:43:46.624779Z", "shell.execute_reply": "2025-03-25T08:43:46.624327Z" } }, "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 = \"GSE94524\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Endometrioid_Cancer\"\n", "in_cohort_dir = \"../../input/GEO/Endometrioid_Cancer/GSE94524\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Endometrioid_Cancer/GSE94524.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Endometrioid_Cancer/gene_data/GSE94524.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Endometrioid_Cancer/clinical_data/GSE94524.csv\"\n", "json_path = \"../../output/preprocess/Endometrioid_Cancer/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "985da75b", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "5c72c7bd", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:43:46.626220Z", "iopub.status.busy": "2025-03-25T08:43:46.626065Z", "iopub.status.idle": "2025-03-25T08:43:46.814136Z", "shell.execute_reply": "2025-03-25T08:43:46.813558Z" } }, "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\"\n", "!Series_summary\t\"This SuperSeries is composed of the SubSeries listed below.\"\n", "!Series_overall_design\t\"Refer to individual Series\"\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": "9d6c1533", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "59ef0d24", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:43:46.815577Z", "iopub.status.busy": "2025-03-25T08:43:46.815241Z", "iopub.status.idle": "2025-03-25T08:43:46.820659Z", "shell.execute_reply": "2025-03-25T08:43:46.820188Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Clinical data file not found at ../../input/GEO/Endometrioid_Cancer/GSE94524/clinical.csv. Skipping clinical feature extraction.\n" ] } ], "source": [ "# Analysis and decisions:\n", "\n", "# 1. Gene Expression Data Availability\n", "# Based on the SuperSeries description, it's likely to contain gene expression data as part of its SubSeries\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "# Reviewing the sample characteristics dictionary\n", "# For trait: We can see 'tissue: endometrioid adenocarcinoma' in row 0\n", "# This indicates the tissue type, which can be used as the trait information\n", "trait_row = 0\n", "\n", "# For age: There is no information about age in the sample characteristics\n", "age_row = None\n", "\n", "# For gender: There is no information about gender in the sample characteristics\n", "gender_row = None\n", "\n", "# 2.2 Data Type Conversion\n", "# For trait:\n", "def convert_trait(value):\n", " if pd.isna(value) or value is None:\n", " return None\n", " \n", " # Extract value after colon if present\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " # Check if value indicates endometrioid cancer\n", " if \"endometrioid\" in value.lower() and \"adenocarcinoma\" in value.lower():\n", " return 1 # Indicates endometrioid cancer\n", " else:\n", " return 0 # Not endometrioid cancer\n", "\n", "# Since age and gender are not available, we'll define placeholder functions\n", "def convert_age(value):\n", " return None\n", "\n", "def convert_gender(value):\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Determine trait availability based on trait_row\n", "is_trait_available = trait_row is not None\n", "\n", "# Save initial cohort info\n", "validate_and_save_cohort_info(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", "# 4. Clinical Feature Extraction\n", "# Check if trait data is available\n", "if trait_row is not None:\n", " # Define the path to the expected clinical data file\n", " clinical_file_path = f\"{in_cohort_dir}/clinical.csv\"\n", " \n", " # Check if the file exists before trying to load it\n", " if os.path.exists(clinical_file_path):\n", " try:\n", " clinical_data = pd.read_csv(clinical_file_path)\n", " \n", " # Extract clinical features\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 resulting dataframe\n", " preview = preview_df(selected_clinical_df)\n", " print(\"Preview of selected clinical features:\")\n", " print(preview)\n", " \n", " # Save the clinical data to the specified path\n", " selected_clinical_df.to_csv(out_clinical_data_file, index=False)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n", " except Exception as e:\n", " print(f\"Error processing clinical data: {e}\")\n", " else:\n", " print(f\"Clinical data file not found at {clinical_file_path}. Skipping clinical feature extraction.\")\n", "else:\n", " print(\"No trait data available, skipping clinical feature extraction.\")\n" ] }, { "cell_type": "markdown", "id": "f73a60ad", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "ef2e7dbe", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:43:46.821983Z", "iopub.status.busy": "2025-03-25T08:43:46.821869Z", "iopub.status.idle": "2025-03-25T08:43:47.212851Z", "shell.execute_reply": "2025-03-25T08:43:47.212375Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Found data marker at line 73\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": "97e5177e", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "4b9bf127", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:43:47.214300Z", "iopub.status.busy": "2025-03-25T08:43:47.214158Z", "iopub.status.idle": "2025-03-25T08:43:47.216271Z", "shell.execute_reply": "2025-03-25T08:43:47.215946Z" } }, "outputs": [], "source": [ "# Examine the gene identifiers in the gene expression data\n", "# Looking at the first line of data, we see numeric identifiers (1, 2, 3, etc.)\n", "# These appear to be numeric probe IDs and not human gene symbols\n", "# Typically human gene symbols would be alphanumeric identifiers like \"BRCA1\", \"TP53\", etc.\n", "# Therefore, these identifiers need to be mapped to gene symbols\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "8e31edbc", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "ccf138fe", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:43:47.217446Z", "iopub.status.busy": "2025-03-25T08:43:47.217334Z", "iopub.status.idle": "2025-03-25T08:43:54.875796Z", "shell.execute_reply": "2025-03-25T08:43:54.875160Z" } }, "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": "b2bd9b41", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "3399a387", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:43:54.877347Z", "iopub.status.busy": "2025-03-25T08:43:54.877207Z", "iopub.status.idle": "2025-03-25T08:43:55.811396Z", "shell.execute_reply": "2025-03-25T08:43:55.810740Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Creating gene mapping from available annotation data\n", "Created mapping with 13569 entries\n", "Applying gene mapping to convert probe data to gene expression data...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalizing gene symbols...\n", "\n", "Preview of gene expression data after mapping:\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", "Shape of gene expression data: (9628, 111)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data saved to ../../output/preprocess/Endometrioid_Cancer/gene_data/GSE94524.csv\n" ] } ], "source": [ "# 1. Analyze the gene annotation dataframe to identify appropriate columns for mapping\n", "# The 'ID' column in gene_annotation contains numeric IDs matching the gene expression data indices\n", "# The 'HUGO' column appears to contain gene symbols, which is what we need for mapping\n", "\n", "# 2. Generate the gene mapping dataframe using the library function\n", "# This is more efficient than processing row by row\n", "print(\"Creating gene mapping from available annotation data\")\n", "mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='HUGO')\n", "\n", "# Check the mapping size\n", "print(f\"Created mapping with {len(mapping_df)} entries\")\n", "\n", "# 3. Apply gene mapping to convert probe-level measurements to gene expression data\n", "print(\"Applying gene mapping to convert probe data to gene expression data...\")\n", "gene_data_mapped = apply_gene_mapping(gene_data, mapping_df)\n", "\n", "# Normalize gene symbols to ensure consistency\n", "print(\"Normalizing gene symbols...\")\n", "gene_data = normalize_gene_symbols_in_index(gene_data_mapped)\n", "\n", "# Preview the resulting gene expression data\n", "print(\"\\nPreview of gene expression data after mapping:\")\n", "print(gene_data.head(5))\n", "print(f\"Shape of gene expression data: {gene_data.shape}\")\n", "\n", "# Save the processed gene expression data\n", "if not os.path.exists(os.path.dirname(out_gene_data_file)):\n", " os.makedirs(os.path.dirname(out_gene_data_file))\n", "gene_data.to_csv(out_gene_data_file)\n", "print(f\"Gene expression data saved to {out_gene_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "45291e5c", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "ee1a4285", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:43:55.813118Z", "iopub.status.busy": "2025-03-25T08:43:55.812976Z", "iopub.status.idle": "2025-03-25T08:43:58.828793Z", "shell.execute_reply": "2025-03-25T08:43:58.828181Z" } }, "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/GSE94524.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/GSE94524.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 }