{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "b031abe0", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:22:37.784788Z", "iopub.status.busy": "2025-03-25T05:22:37.784683Z", "iopub.status.idle": "2025-03-25T05:22:37.985877Z", "shell.execute_reply": "2025-03-25T05:22:37.985406Z" } }, "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 = \"Glioblastoma\"\n", "cohort = \"GSE249289\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Glioblastoma\"\n", "in_cohort_dir = \"../../input/GEO/Glioblastoma/GSE249289\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Glioblastoma/GSE249289.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Glioblastoma/gene_data/GSE249289.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Glioblastoma/clinical_data/GSE249289.csv\"\n", "json_path = \"../../output/preprocess/Glioblastoma/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "633ab846", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "df666366", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:22:37.987730Z", "iopub.status.busy": "2025-03-25T05:22:37.987542Z", "iopub.status.idle": "2025-03-25T05:22:38.136117Z", "shell.execute_reply": "2025-03-25T05:22:38.135501Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Gene expression profiles of glioblastoma tumorspheres cultured in diverse platforms\"\n", "!Series_summary\t\"We studied five patients with IDH1 wild-type glioblastoma who were newly diagnosed with no treatment history via surgery, chemotherapy, or radiotherapy. Patient-derived glioblastoma tumorspheres (TSs) were established from fresh tissue specimens, and they were cultured in divserse platforms.\"\n", "!Series_overall_design\t\"Gene expression profiles of five glioblastoma tumorspheres cultured in diverse platforms (collagen, normal ECM, tumor ECM, and mouse xenograft)\"\n", "Sample Characteristics Dictionary:\n", "{0: ['tissue: Brain'], 1: ['Sex: Male', 'Sex: Female'], 2: ['age: 61', 'age: 56', 'age: 57', 'age: 67'], 3: ['tumorsphere: TS13-20', 'tumorsphere: TS13-64', 'tumorsphere: TS14-08', 'tumorsphere: TS14-15', 'tumorsphere: TS15-88'], 4: ['culture platform: Collagen', 'culture platform: nECM', 'culture platform: tECM', 'culture platform: mouse xenograft']}\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": "331a2545", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "d8242072", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:22:38.138042Z", "iopub.status.busy": "2025-03-25T05:22:38.137879Z", "iopub.status.idle": "2025-03-25T05:22:38.145707Z", "shell.execute_reply": "2025-03-25T05:22:38.144963Z" } }, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Let's start by analyzing the data availability\n", "\n", "# 1. Gene Expression Data Availability\n", "# Based on the Series title and summary, this dataset appears to contain gene expression data\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# Looking at the Sample Characteristics Dictionary:\n", "\n", "# 2.1 Trait (Glioblastoma)\n", "# Since all subjects have glioblastoma, we can use tumorsphere ID at index 3 as our trait variable\n", "trait_row = 3 # tumorsphere ID\n", "\n", "def convert_trait(value):\n", " if not value or ':' not in value:\n", " return None\n", " # Extract tumorsphere ID\n", " ts_id = value.split(\":\", 1)[1].strip()\n", " # For simplicity in this study, return 1 since all samples are glioblastoma\n", " return 1\n", "\n", "# 2.2 Age information is at index 2\n", "age_row = 2\n", "\n", "def convert_age(value):\n", " if not value or ':' not in value:\n", " return None\n", " # Extract age value after colon\n", " age_str = value.split(\":\", 1)[1].strip()\n", " try:\n", " # Convert to integer (continuous value)\n", " return int(age_str)\n", " except ValueError:\n", " return None\n", "\n", "# 2.3 Gender information is at index 1\n", "gender_row = 1\n", "\n", "def convert_gender(value):\n", " if not value or ':' not in value:\n", " return None\n", " # Extract gender value after colon\n", " gender = value.split(\":\", 1)[1].strip().lower()\n", " # Convert to binary: 0 for female, 1 for male\n", " if gender == 'female':\n", " return 0\n", " elif gender == 'male':\n", " return 1\n", " else:\n", " return None\n", "\n", "# 3. Save Metadata\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", "# 4. Clinical Feature Extraction\n", "# Skip this step as we don't have access to the clinical_data from a previous step\n", "# This would need to be completed when the clinical_data is available\n" ] }, { "cell_type": "markdown", "id": "5fa2d966", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "25483757", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:22:38.147426Z", "iopub.status.busy": "2025-03-25T05:22:38.147296Z", "iopub.status.idle": "2025-03-25T05:22:38.405915Z", "shell.execute_reply": "2025-03-25T05:22:38.405242Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Found data marker at line 62\n", "Header line: \"ID_REF\"\t\"GSM7933102\"\t\"GSM7933103\"\t\"GSM7933104\"\t\"GSM7933105\"\t\"GSM7933106\"\t\"GSM7933107\"\t\"GSM7933108\"\t\"GSM7933109\"\t\"GSM7933110\"\t\"GSM7933111\"\t\"GSM7933112\"\t\"GSM7933113\"\t\"GSM7933114\"\t\"GSM7933115\"\t\"GSM7933116\"\t\"GSM7933117\"\t\"GSM7933118\"\t\"GSM7933119\"\t\"GSM7933120\"\t\"GSM7933121\"\t\"GSM7933122\"\t\"GSM7933123\"\t\"GSM7933124\"\t\"GSM7933125\"\t\"GSM7933126\"\t\"GSM7933127\"\t\"GSM7933128\"\t\"GSM7933129\"\t\"GSM7933130\"\t\"GSM7933131\"\t\"GSM7933132\"\t\"GSM7933133\"\t\"GSM7933134\"\t\"GSM7933135\"\t\"GSM7933136\"\t\"GSM7933137\"\t\"GSM7933138\"\t\"GSM7933139\"\t\"GSM7933140\"\t\"GSM7933141\"\t\"GSM7933142\"\t\"GSM7933143\"\t\"GSM7933144\"\t\"GSM7933145\"\t\"GSM7933146\"\t\"GSM7933147\"\t\"GSM7933148\"\n", "First data line: \"ILMN_1343291\"\t36765.52574\t36765.52574\t34572.79785\t35950.13809\t36765.52574\t37899.98532\t39162.20468\t37232.73\t37899.98532\t39162.20468\t39162.20468\t39162.20468\t39162.20468\t39162.20468\t37232.73\t39162.20468\t36356.66553\t39162.20468\t30675.89726\t27449.77672\t10234.08017\t28621.69313\t37232.73\t39162.20468\t34940.55083\t35950.13809\t36356.66553\t34940.55083\t35500.03298\t33181.27779\t15286.09945\t37899.98532\t37899.98532\t39162.20468\t35950.13809\t35950.13809\t34940.55083\t11345.14851\t12057.23963\t13745.00826\t28077.30917\t7760.55049\t30675.89726\t37232.73\t37899.98532\t36356.66553\t37899.98532\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Index(['ILMN_1343291', 'ILMN_1343295', 'ILMN_1651199', 'ILMN_1651209',\n", " 'ILMN_1651210', 'ILMN_1651221', 'ILMN_1651228', 'ILMN_1651229',\n", " 'ILMN_1651230', 'ILMN_1651232', 'ILMN_1651235', 'ILMN_1651236',\n", " 'ILMN_1651237', 'ILMN_1651238', 'ILMN_1651249', 'ILMN_1651253',\n", " 'ILMN_1651254', 'ILMN_1651259', 'ILMN_1651260', 'ILMN_1651262'],\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": "7e3d63e5", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "b7a22735", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:22:38.407394Z", "iopub.status.busy": "2025-03-25T05:22:38.407267Z", "iopub.status.idle": "2025-03-25T05:22:38.409789Z", "shell.execute_reply": "2025-03-25T05:22:38.409298Z" } }, "outputs": [], "source": [ "# The gene identifiers start with \"ILMN_\" which indicates they are Illumina probe IDs,\n", "# not human gene symbols. Illumina IDs need to be mapped to gene symbols for biological interpretation.\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "1be1ceb6", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "23cf565d", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:22:38.411123Z", "iopub.status.busy": "2025-03-25T05:22:38.411014Z", "iopub.status.idle": "2025-03-25T05:22:39.348833Z", "shell.execute_reply": "2025-03-25T05:22:39.348195Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Examining SOFT file structure:\n", "Line 0: ^DATABASE = GeoMiame\n", "Line 1: !Database_name = Gene Expression Omnibus (GEO)\n", "Line 2: !Database_institute = NCBI NLM NIH\n", "Line 3: !Database_web_link = http://www.ncbi.nlm.nih.gov/geo\n", "Line 4: !Database_email = geo@ncbi.nlm.nih.gov\n", "Line 5: ^SERIES = GSE249289\n", "Line 6: !Series_title = Gene expression profiles of glioblastoma tumorspheres cultured in diverse platforms\n", "Line 7: !Series_geo_accession = GSE249289\n", "Line 8: !Series_status = Public on Dec 09 2023\n", "Line 9: !Series_submission_date = Dec 04 2023\n", "Line 10: !Series_last_update_date = Dec 09 2023\n", "Line 11: !Series_summary = We studied five patients with IDH1 wild-type glioblastoma who were newly diagnosed with no treatment history via surgery, chemotherapy, or radiotherapy. Patient-derived glioblastoma tumorspheres (TSs) were established from fresh tissue specimens, and they were cultured in divserse platforms.\n", "Line 12: !Series_overall_design = Gene expression profiles of five glioblastoma tumorspheres cultured in diverse platforms (collagen, normal ECM, tumor ECM, and mouse xenograft)\n", "Line 13: !Series_type = Expression profiling by array\n", "Line 14: !Series_contributor = Junseong,,Park\n", "Line 15: !Series_contributor = Seok-Gu,,Kang\n", "Line 16: !Series_sample_id = GSM7933102\n", "Line 17: !Series_sample_id = GSM7933103\n", "Line 18: !Series_sample_id = GSM7933104\n", "Line 19: !Series_sample_id = GSM7933105\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene annotation preview:\n", "{'ID': ['ILMN_1343048', 'ILMN_1343049', 'ILMN_1343050', 'ILMN_1343052', 'ILMN_1343059'], 'Species': [nan, nan, nan, nan, nan], 'Source': [nan, nan, nan, nan, nan], 'Search_Key': [nan, nan, nan, nan, nan], 'Transcript': [nan, nan, nan, nan, nan], 'ILMN_Gene': [nan, nan, nan, nan, nan], 'Source_Reference_ID': [nan, nan, nan, nan, nan], 'RefSeq_ID': [nan, nan, nan, nan, nan], 'Unigene_ID': [nan, nan, nan, nan, nan], 'Entrez_Gene_ID': [nan, nan, nan, nan, nan], 'GI': [nan, nan, nan, nan, nan], 'Accession': [nan, nan, nan, nan, nan], 'Symbol': ['phage_lambda_genome', 'phage_lambda_genome', 'phage_lambda_genome:low', 'phage_lambda_genome:low', 'thrB'], 'Protein_Product': [nan, nan, nan, nan, 'thrB'], 'Probe_Id': [nan, nan, nan, nan, nan], 'Array_Address_Id': [5090180, 6510136, 7560739, 1450438, 1240647], 'Probe_Type': [nan, nan, nan, nan, nan], 'Probe_Start': [nan, nan, nan, nan, nan], 'SEQUENCE': ['GAATAAAGAACAATCTGCTGATGATCCCTCCGTGGATCTGATTCGTGTAA', 'CCATGTGATACGAGGGCGCGTAGTTTGCATTATCGTTTTTATCGTTTCAA', 'CCGACAGATGTATGTAAGGCCAACGTGCTCAAATCTTCATACAGAAAGAT', 'TCTGTCACTGTCAGGAAAGTGGTAAAACTGCAACTCAATTACTGCAATGC', 'CTTGTGCCTGAGCTGTCAAAAGTAGAGCACGTCGCCGAGATGAAGGGCGC'], 'Chromosome': [nan, nan, nan, nan, nan], 'Probe_Chr_Orientation': [nan, nan, nan, nan, nan], 'Probe_Coordinates': [nan, nan, nan, nan, nan], 'Cytoband': [nan, nan, nan, nan, nan], 'Definition': [nan, nan, nan, nan, nan], 'Ontology_Component': [nan, nan, nan, nan, nan], 'Ontology_Process': [nan, nan, nan, nan, nan], 'Ontology_Function': [nan, nan, nan, nan, nan], 'Synonyms': [nan, nan, nan, nan, nan], 'Obsolete_Probe_Id': [nan, nan, nan, nan, nan], 'GB_ACC': [nan, nan, nan, nan, nan]}\n" ] } ], "source": [ "# 1. Let's first examine the structure of the SOFT file before trying to parse it\n", "import gzip\n", "\n", "# Look at the first few lines of the SOFT file to understand its structure\n", "print(\"Examining SOFT file structure:\")\n", "try:\n", " with gzip.open(soft_file, 'rt') as file:\n", " # Read first 20 lines to understand the file structure\n", " for i, line in enumerate(file):\n", " if i < 20:\n", " print(f\"Line {i}: {line.strip()}\")\n", " else:\n", " break\n", "except Exception as e:\n", " print(f\"Error reading SOFT file: {e}\")\n", "\n", "# 2. Now let's try a more robust approach to extract the gene annotation\n", "# Instead of using the library function which failed, we'll implement a custom approach\n", "try:\n", " # First, look for the platform section which contains gene annotation\n", " platform_data = []\n", " with gzip.open(soft_file, 'rt') as file:\n", " in_platform_section = False\n", " for line in file:\n", " if line.startswith('^PLATFORM'):\n", " in_platform_section = True\n", " continue\n", " if in_platform_section and line.startswith('!platform_table_begin'):\n", " # Next line should be the header\n", " header = next(file).strip()\n", " platform_data.append(header)\n", " # Read until the end of the platform table\n", " for table_line in file:\n", " if table_line.startswith('!platform_table_end'):\n", " break\n", " platform_data.append(table_line.strip())\n", " break\n", " \n", " # If we found platform data, convert it to a DataFrame\n", " if platform_data:\n", " import pandas as pd\n", " import io\n", " platform_text = '\\n'.join(platform_data)\n", " gene_annotation = pd.read_csv(io.StringIO(platform_text), delimiter='\\t', \n", " low_memory=False, on_bad_lines='skip')\n", " print(\"\\nGene annotation preview:\")\n", " print(preview_df(gene_annotation))\n", " else:\n", " print(\"Could not find platform table in SOFT file\")\n", " \n", " # Try an alternative approach - extract mapping from other sections\n", " with gzip.open(soft_file, 'rt') as file:\n", " for line in file:\n", " if 'ANNOTATION information' in line or 'annotation information' in line:\n", " print(f\"Found annotation information: {line.strip()}\")\n", " if line.startswith('!Platform_title') or line.startswith('!platform_title'):\n", " print(f\"Platform title: {line.strip()}\")\n", " \n", "except Exception as e:\n", " print(f\"Error processing gene annotation: {e}\")\n" ] }, { "cell_type": "markdown", "id": "af6facfb", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "bb4ce1cd", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:22:39.350311Z", "iopub.status.busy": "2025-03-25T05:22:39.350181Z", "iopub.status.idle": "2025-03-25T05:22:40.059894Z", "shell.execute_reply": "2025-03-25T05:22:40.059233Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Converted gene expression data preview:\n", " GSM7933102 GSM7933103 GSM7933104 GSM7933105 GSM7933106 GSM7933107 \\\n", "Gene \n", "A1BG 51.16928 66.11620 35.05003 25.08680 17.77941 34.71231 \n", "A1CF -5.32805 -6.33568 9.02714 31.75687 -5.53339 5.60693 \n", "A26C3 -9.95525 -7.17041 -15.59057 -0.76042 32.17539 -13.53330 \n", "A2BP1 -10.09491 -32.64002 -22.01939 -9.12635 -39.38100 -38.72339 \n", "A2LD1 26.42643 18.98107 25.65493 8.60538 14.89496 -4.90494 \n", "\n", " GSM7933108 GSM7933109 GSM7933110 GSM7933111 ... GSM7933139 \\\n", "Gene ... \n", "A1BG 36.23326 45.66879 69.21304 32.32465 ... 2221.74373 \n", "A1CF 2.77058 17.76274 -2.80695 3.50213 ... 6571.60134 \n", "A26C3 1.43785 -0.70152 -15.03475 -11.21337 ... 261.59080 \n", "A2BP1 -17.16718 -23.24092 -37.78715 -24.95582 ... 15.52601 \n", "A2LD1 -15.96368 -8.42864 -5.22266 0.90460 ... -8.23763 \n", "\n", " GSM7933140 GSM7933141 GSM7933142 GSM7933143 GSM7933144 \\\n", "Gene \n", "A1BG 2589.88546 2096.12002 90.49209 774.83814 40.89988 \n", "A1CF 6768.58993 5722.92118 29.27145 9.24382 12.88883 \n", "A26C3 251.33967 -1.40063 19.48311 194.58376 -0.33078 \n", "A2BP1 15.41099 -5.13057 4629.27469 15447.06996 -25.66190 \n", "A2LD1 -8.06392 -11.59555 289.35194 15.02413 34.25155 \n", "\n", " GSM7933145 GSM7933146 GSM7933147 GSM7933148 \n", "Gene \n", "A1BG 42.31677 36.75294 121.15985 50.34716 \n", "A1CF 8.45594 11.13380 4.67670 13.55316 \n", "A26C3 -23.54697 5.99049 0.03941 -11.39096 \n", "A2BP1 -29.37835 -20.76313 2129.63482 2708.92741 \n", "A2LD1 30.55513 36.66601 73.59628 138.48255 \n", "\n", "[5 rows x 47 columns]\n", "Shape of gene expression data: (21464, 47)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data saved to ../../output/preprocess/Glioblastoma/gene_data/GSE249289.csv\n" ] } ], "source": [ "# 1. First, determine the mapping columns\n", "# From the previous outputs, we can see:\n", "# - In gene_data, gene IDs are in the format \"ILMN_XXXXXXX\"\n", "# - In gene_annotation, these IDs are in the \"ID\" column\n", "# - The gene symbols are in the \"Symbol\" column\n", "\n", "# 2. Create the gene mapping dataframe\n", "# Extract the relevant columns (ID and Symbol) for mapping\n", "mapping_df = gene_annotation[['ID', 'Symbol']].copy()\n", "\n", "# Filter out entries with empty gene symbols and convert to string type\n", "mapping_df = mapping_df.dropna(subset=['Symbol'])\n", "mapping_df = mapping_df.astype({'ID': 'str', 'Symbol': 'str'})\n", "\n", "# Rename Symbol column to Gene to match the expected structure in apply_gene_mapping function\n", "mapping_df = mapping_df.rename(columns={'Symbol': 'Gene'})\n", "\n", "# 3. Apply the gene mapping to convert probe-level measurements to gene expression\n", "# Use the library function to handle the many-to-many relationship between probes and genes\n", "gene_data = apply_gene_mapping(gene_data, mapping_df)\n", "\n", "# Verify the result by checking the head of the gene_data dataframe\n", "print(\"Converted gene expression data preview:\")\n", "print(gene_data.head())\n", "print(f\"Shape of gene expression data: {gene_data.shape}\")\n", "\n", "# Save the gene expression data to the output 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\"Gene expression data saved to {out_gene_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "355b3c96", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "16232062", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:22:40.061367Z", "iopub.status.busy": "2025-03-25T05:22:40.061229Z", "iopub.status.idle": "2025-03-25T05:22:47.584216Z", "shell.execute_reply": "2025-03-25T05:22:47.583645Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Loaded gene data shape: (21464, 47)\n", "Gene data shape after normalization: (20259, 47)\n", "Sample gene symbols after normalization: ['A1BG', 'A1BG-AS1', 'A1CF', 'A2M', 'A2ML1', 'A3GALT2', 'A4GALT', 'A4GNT', 'AAA1', 'AAAS']\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data saved to ../../output/preprocess/Glioblastoma/gene_data/GSE249289.csv\n", "Clinical data file not found, generating it now\n", "Clinical data shape: (3, 47)\n", "Clinical data preview:\n", " GSM7933102 GSM7933103 GSM7933104 GSM7933105 GSM7933106 \\\n", "Glioblastoma 1.0 1.0 1.0 1.0 1.0 \n", "Age 61.0 61.0 61.0 61.0 61.0 \n", "Gender 1.0 1.0 1.0 1.0 1.0 \n", "\n", " GSM7933107 GSM7933108 GSM7933109 GSM7933110 GSM7933111 ... \\\n", "Glioblastoma 1.0 1.0 1.0 1.0 1.0 ... \n", "Age 61.0 61.0 61.0 61.0 61.0 ... \n", "Gender 1.0 1.0 1.0 1.0 1.0 ... \n", "\n", " GSM7933139 GSM7933140 GSM7933141 GSM7933142 GSM7933143 \\\n", "Glioblastoma 1.0 1.0 1.0 1.0 1.0 \n", "Age 67.0 67.0 67.0 67.0 67.0 \n", "Gender 1.0 1.0 1.0 1.0 1.0 \n", "\n", " GSM7933144 GSM7933145 GSM7933146 GSM7933147 GSM7933148 \n", "Glioblastoma 1.0 1.0 1.0 1.0 1.0 \n", "Age 61.0 61.0 61.0 61.0 61.0 \n", "Gender 1.0 1.0 1.0 1.0 1.0 \n", "\n", "[3 rows x 47 columns]\n", "Linked data shape: (47, 20262)\n", "Linked data preview (first 5 rows, first 5 columns):\n", " Glioblastoma Age Gender A1BG A1BG-AS1\n", "GSM7933102 1.0 61.0 1.0 51.16928 11.51965\n", "GSM7933103 1.0 61.0 1.0 66.11620 14.79927\n", "GSM7933104 1.0 61.0 1.0 35.05003 19.33287\n", "GSM7933105 1.0 61.0 1.0 25.08680 -1.83802\n", "GSM7933106 1.0 61.0 1.0 17.77941 16.71515\n", "\n", "Missing values before handling:\n", " Trait (Glioblastoma) missing: 0 out of 47\n", " Age missing: 0 out of 47\n", " Gender missing: 0 out of 47\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: (47, 20262)\n", "Quartiles for 'Glioblastoma':\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 'Glioblastoma' in this dataset is severely biased.\n", "\n", "Quartiles for 'Age':\n", " 25%: 57.0\n", " 50% (Median): 61.0\n", " 75%: 61.0\n", "Min: 56.0\n", "Max: 67.0\n", "The distribution of the feature 'Age' in this dataset is fine.\n", "\n", "For the feature 'Gender', the least common label is '0.0' with 13 occurrences. This represents 27.66% of the dataset.\n", "The distribution of the feature 'Gender' in this dataset is fine.\n", "\n", "Data was determined to be unusable or empty and was not saved\n" ] } ], "source": [ "# 1. Load the gene expression data saved in step 6\n", "gene_data = pd.read_csv(out_gene_data_file, index_col=0)\n", "print(f\"Loaded gene data shape: {gene_data.shape}\")\n", "\n", "# Normalize gene symbols using NCBI Gene database\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\"Sample gene symbols after normalization: {list(normalized_gene_data.index[:10])}\")\n", "\n", "# Save the normalized gene data (overwrite the previous file with normalized 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. Generate and save clinical data if it doesn't exist\n", "if not os.path.exists(out_clinical_data_file):\n", " print(\"Clinical data file not found, generating it now\")\n", " # Get the SOFT and matrix files again\n", " soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", " \n", " # Get the clinical 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", " # Define conversion functions based on the sample characteristics from step 1\n", " def convert_trait(value):\n", " if not value or ':' not in value:\n", " return None\n", " # Extract tumorsphere ID\n", " ts_id = value.split(\":\", 1)[1].strip()\n", " # For simplicity in this study, return 1 since all samples are glioblastoma\n", " return 1\n", "\n", " def convert_age(value):\n", " if not value or ':' not in value:\n", " return None\n", " # Extract age value after colon\n", " age_str = value.split(\":\", 1)[1].strip()\n", " try:\n", " # Convert to integer (continuous value)\n", " return int(age_str)\n", " except ValueError:\n", " return None\n", "\n", " def convert_gender(value):\n", " if not value or ':' not in value:\n", " return None\n", " # Extract gender value after colon\n", " gender = value.split(\":\", 1)[1].strip().lower()\n", " # Convert to binary: 0 for female, 1 for male\n", " if gender == 'female':\n", " return 0\n", " elif gender == 'male':\n", " return 1\n", " else:\n", " return None\n", " \n", " # Define row indices based on sample characteristics from step 1\n", " trait_row = 3 # tumorsphere ID\n", " age_row = 2\n", " gender_row = 1\n", " \n", " # Extract clinical features\n", " clinical_features = geo_select_clinical_features(\n", " 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", " # Save the clinical features\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " clinical_features.to_csv(out_clinical_data_file)\n", " clinical_df = clinical_features\n", "else:\n", " clinical_df = pd.read_csv(out_clinical_data_file, index_col=0)\n", "\n", "print(f\"Clinical data shape: {clinical_df.shape}\")\n", "print(\"Clinical data preview:\")\n", "print(clinical_df.head())\n", "\n", "# 3. Link clinical and genetic data\n", "linked_data = geo_link_clinical_genetic_data(clinical_df, normalized_gene_data)\n", "print(f\"Linked data shape: {linked_data.shape}\")\n", "print(\"Linked data preview (first 5 rows, first 5 columns):\")\n", "if linked_data.shape[1] >= 5:\n", " print(linked_data.iloc[:5, :5])\n", "else:\n", " print(linked_data.head())\n", "\n", "# 4. Handle missing values\n", "print(\"\\nMissing 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", "if gene_cols:\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=len(normalized_gene_data) > 0, \n", " is_trait_available=True, \n", " is_biased=is_trait_biased, \n", " df=cleaned_data,\n", " note=f\"Dataset contains gene expression data for {trait} analysis.\"\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\")" ] } ], "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 }