{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "bf38b6c4", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:21:46.855782Z", "iopub.status.busy": "2025-03-25T05:21:46.855675Z", "iopub.status.idle": "2025-03-25T05:21:47.021415Z", "shell.execute_reply": "2025-03-25T05:21:47.021023Z" } }, "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 = \"GSE159000\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Glioblastoma\"\n", "in_cohort_dir = \"../../input/GEO/Glioblastoma/GSE159000\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Glioblastoma/GSE159000.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Glioblastoma/gene_data/GSE159000.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Glioblastoma/clinical_data/GSE159000.csv\"\n", "json_path = \"../../output/preprocess/Glioblastoma/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "974eadd7", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "1847adc1", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:21:47.022932Z", "iopub.status.busy": "2025-03-25T05:21:47.022768Z", "iopub.status.idle": "2025-03-25T05:21:47.142353Z", "shell.execute_reply": "2025-03-25T05:21:47.142014Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Gene expression profiles of non-recurrent human glioblastoma tumorspheres\"\n", "!Series_summary\t\"Samples were obtained from 23 non-recurrent GBM patients treated at Severance Hospital\"\n", "!Series_overall_design\t\"Samples were obtained from 23 non-recurrent GBM patients treated at Severance Hospital\"\n", "Sample Characteristics Dictionary:\n", "{0: ['tissue: Brain'], 1: ['Sex: M', 'Sex: F'], 2: ['age: 53', 'age: 51', 'age: 68', 'age: 61', 'age: 49', 'age: 56', 'age: 65', 'age: 11', 'age: 69', 'age: 70', 'age: 57', 'age: 67', 'age: 52', 'age: 42', 'age: 75', 'age: 50', 'age: 48', 'age: 62']}\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": "906307e0", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "08264710", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:21:47.143582Z", "iopub.status.busy": "2025-03-25T05:21:47.143466Z", "iopub.status.idle": "2025-03-25T05:21:47.148021Z", "shell.execute_reply": "2025-03-25T05:21:47.147706Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Initial filtering completed. Cohort information saved to ../../output/preprocess/Glioblastoma/cohort_info.json\n", "Dataset contains gene expression data: True\n", "Dataset contains trait data: True\n" ] } ], "source": [ "import pandas as pd\n", "import numpy as np\n", "import os\n", "from typing import Optional, List, Dict, Any, Callable\n", "\n", "# 1. Determine if gene expression data is available\n", "is_gene_available = True # Gene expression data is likely available as the title suggests \"Gene expression profiles\"\n", "\n", "# 2. Determine data availability and conversion functions\n", "# 2.1 Data Availability\n", "# We don't have an explicit row that identifies GBM status since all patients have it\n", "trait_row = None # Trait is not explicitly coded in the characteristics\n", "age_row = 2 # Age information is in row 2\n", "gender_row = 1 # Gender information is in row 1\n", "\n", "# 2.2 Data Type Conversion Functions\n", "def convert_trait(value: str) -> Optional[int]:\n", " \"\"\"Convert trait value to binary format (1 for having the trait).\"\"\"\n", " # All patients have glioblastoma according to the background information\n", " return 1\n", "\n", "def convert_age(value: str) -> Optional[float]:\n", " \"\"\"Convert age value to continuous format.\"\"\"\n", " if not value or \":\" not in value:\n", " return None\n", " \n", " try:\n", " # Extract value after the colon and convert to float\n", " age_str = value.split(\":\", 1)[1].strip()\n", " return float(age_str)\n", " except (ValueError, IndexError):\n", " return None\n", "\n", "def convert_gender(value: str) -> Optional[int]:\n", " \"\"\"Convert gender value to binary format (0 for female, 1 for male).\"\"\"\n", " if not value or \":\" not in value:\n", " return None\n", " \n", " # Extract value after the colon\n", " gender_str = value.split(\":\", 1)[1].strip().upper()\n", " \n", " if gender_str == \"F\":\n", " return 0\n", " elif gender_str == \"M\":\n", " return 1\n", " else:\n", " return None\n", "\n", "# 3. Save metadata\n", "# Since trait_row is None, we rely on background information to determine trait availability\n", "# Background information states all patients have GBM\n", "is_trait_available = True\n", "\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", "# No need for clinical feature extraction since we don't have a proper clinical_data dataframe\n", "# and trait_row is None. We will handle this in later steps with the actual gene expression data.\n", "print(f\"Initial filtering completed. Cohort information saved to {json_path}\")\n", "print(f\"Dataset contains gene expression data: {is_gene_available}\")\n", "print(f\"Dataset contains trait data: {is_trait_available}\")\n" ] }, { "cell_type": "markdown", "id": "ddc3f985", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "00dd182c", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:21:47.149072Z", "iopub.status.busy": "2025-03-25T05:21:47.148959Z", "iopub.status.idle": "2025-03-25T05:21:47.333616Z", "shell.execute_reply": "2025-03-25T05:21:47.333264Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Found data marker at line 60\n", "Header line: \"ID_REF\"\t\"GSM4817125\"\t\"GSM4817126\"\t\"GSM4817127\"\t\"GSM4817128\"\t\"GSM4817129\"\t\"GSM4817130\"\t\"GSM4817131\"\t\"GSM4817132\"\t\"GSM4817133\"\t\"GSM4817134\"\t\"GSM4817135\"\t\"GSM4817136\"\t\"GSM4817137\"\t\"GSM4817138\"\t\"GSM4817139\"\t\"GSM4817140\"\t\"GSM4817141\"\t\"GSM4817142\"\t\"GSM4817143\"\t\"GSM4817144\"\t\"GSM4817145\"\t\"GSM4817146\"\t\"GSM4817147\"\t\"GSM4817148\"\t\"GSM4817149\"\t\"GSM4817150\"\t\"GSM4817151\"\t\"GSM4817152\"\t\"GSM4817153\"\t\"GSM4817154\"\t\"GSM4817155\"\t\"GSM4817156\"\t\"GSM4817157\"\t\"GSM4817158\"\n", "First data line: \"ILMN_1343291\"\t13.86646235\t13.79568344\t13.89969423\t14.14217028\t13.80018446\t13.89187435\t13.78265968\t13.77749268\t13.82485582\t14.29516183\t14.14268467\t14.04071604\t13.8376134\t13.94562018\t13.89574802\t13.71926472\t13.99971089\t13.86952764\t13.8631937\t14.13215749\t14.21943704\t14.1160394\t14.2703063\t14.10571294\t14.07107712\t15.75998414\t15.69032577\t13.5802939\t13.7254719\t14.27520582\t14.12386841\t14.08193093\t14.20840815\t14.11377002\n", "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": "2bdc6af3", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "66b411b9", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:21:47.334840Z", "iopub.status.busy": "2025-03-25T05:21:47.334726Z", "iopub.status.idle": "2025-03-25T05:21:47.336622Z", "shell.execute_reply": "2025-03-25T05:21:47.336323Z" } }, "outputs": [], "source": [ "# Examining the gene identifiers from the previous step\n", "# The identifiers begin with \"ILMN_\" which indicates they are Illumina probe IDs\n", "# These are not human gene symbols but microarray probe identifiers that need to be mapped to gene symbols\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "b92f9123", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "41d28210", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:21:47.337714Z", "iopub.status.busy": "2025-03-25T05:21:47.337604Z", "iopub.status.idle": "2025-03-25T05:21:48.370682Z", "shell.execute_reply": "2025-03-25T05:21:48.370028Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Examining SOFT file structure:\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "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 = GSE159000\n", "Line 6: !Series_title = Gene expression profiles of non-recurrent human glioblastoma tumorspheres\n", "Line 7: !Series_geo_accession = GSE159000\n", "Line 8: !Series_status = Public on Oct 06 2020\n", "Line 9: !Series_submission_date = Oct 05 2020\n", "Line 10: !Series_last_update_date = Jan 06 2023\n", "Line 11: !Series_pubmed_id = 36497392\n", "Line 12: !Series_summary = Samples were obtained from 23 non-recurrent GBM patients treated at Severance Hospital\n", "Line 13: !Series_overall_design = Samples were obtained from 23 non-recurrent GBM patients treated at Severance Hospital\n", "Line 14: !Series_type = Expression profiling by array\n", "Line 15: !Series_contributor = Junseong,,Park\n", "Line 16: !Series_contributor = Seok-Gu,,Kang\n", "Line 17: !Series_sample_id = GSM4817125\n", "Line 18: !Series_sample_id = GSM4817126\n", "Line 19: !Series_sample_id = GSM4817127\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": "ee947477", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "23b20cbd", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:21:48.372630Z", "iopub.status.busy": "2025-03-25T05:21:48.372471Z", "iopub.status.idle": "2025-03-25T05:21:48.498802Z", "shell.execute_reply": "2025-03-25T05:21:48.498160Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Using ID as probe identifier and Symbol as gene symbol for mapping\n", "Created mapping dataframe with 44837 rows\n", "First 5 rows of mapping data:\n", " ID Gene\n", "0 ILMN_1343048 phage_lambda_genome\n", "1 ILMN_1343049 phage_lambda_genome\n", "2 ILMN_1343050 phage_lambda_genome:low\n", "3 ILMN_1343052 phage_lambda_genome:low\n", "4 ILMN_1343059 thrB\n", "Gene expression data now contains 21461 genes and 34 samples\n", "First 5 genes:\n", "Index(['A1BG', 'A1CF', 'A26C3', 'A2BP1', 'A2LD1'], dtype='object', name='Gene')\n", "\n", "Summary statistics of the first 5 samples:\n", " GSM4817125 GSM4817126 GSM4817127 GSM4817128 GSM4817129\n", "count 21461.000000 21461.000000 21461.000000 21461.000000 21461.000000\n", "mean 11.943513 11.731053 11.852193 13.916900 11.669797\n", "std 7.062177 6.932295 7.017661 8.364070 6.894732\n", "min 3.728899 3.678967 3.619433 3.851842 3.406408\n", "25% 7.504871 7.378888 7.285051 7.906167 6.942607\n", "50% 7.977699 7.852510 8.114710 10.633058 8.396161\n", "75% 15.040409 14.783763 14.627267 16.091235 14.020732\n", "max 127.364569 125.033519 123.655364 132.706997 117.689524\n" ] } ], "source": [ "# Identifying which columns to use for mapping\n", "# From the annotation preview, we can see:\n", "# - 'ID' column contains probe IDs (ILMN_*) which match the gene expression index\n", "# - 'Symbol' column contains gene symbols\n", "\n", "# Step 1: Identify columns for mapping\n", "prob_col = 'ID'\n", "gene_col = 'Symbol'\n", "\n", "print(f\"Using {prob_col} as probe identifier and {gene_col} as gene symbol for mapping\")\n", "\n", "# Step 2: Create gene mapping dataframe\n", "mapping_data = get_gene_mapping(gene_annotation, prob_col, gene_col)\n", "print(f\"Created mapping dataframe with {len(mapping_data)} rows\")\n", "print(f\"First 5 rows of mapping data:\")\n", "print(mapping_data.head(5))\n", "\n", "# Step 3: Apply gene mapping to convert probe data to gene expression data\n", "gene_data = apply_gene_mapping(gene_data, mapping_data)\n", "print(f\"Gene expression data now contains {len(gene_data)} genes and {gene_data.shape[1]} samples\")\n", "print(f\"First 5 genes:\")\n", "print(gene_data.index[:5])\n", "\n", "# Get a sense of the data distribution\n", "print(\"\\nSummary statistics of the first 5 samples:\")\n", "print(gene_data.iloc[:, :5].describe())\n" ] }, { "cell_type": "markdown", "id": "5fac3ab5", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "7934958e", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:21:48.500839Z", "iopub.status.busy": "2025-03-25T05:21:48.500687Z", "iopub.status.idle": "2025-03-25T05:21:55.526701Z", "shell.execute_reply": "2025-03-25T05:21:55.526105Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape after normalization: (20257, 34)\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/GSE159000.csv\n", "Clinical data shape: (3, 34)\n", "Clinical data preview:\n", " GSM4817125 GSM4817126 GSM4817127 GSM4817128 GSM4817129 \\\n", "Glioblastoma 1.0 1.0 1.0 1.0 1.0 \n", "Age 53.0 51.0 51.0 68.0 61.0 \n", "Gender 1.0 0.0 0.0 1.0 1.0 \n", "\n", " GSM4817130 GSM4817131 GSM4817132 GSM4817133 GSM4817134 ... \\\n", "Glioblastoma 1.0 1.0 1.0 1.0 1.0 ... \n", "Age 61.0 49.0 49.0 61.0 56.0 ... \n", "Gender 1.0 0.0 0.0 1.0 0.0 ... \n", "\n", " GSM4817149 GSM4817150 GSM4817151 GSM4817152 GSM4817153 \\\n", "Glioblastoma 1.0 1.0 1.0 1.0 1.0 \n", "Age 67.0 52.0 42.0 75.0 61.0 \n", "Gender 1.0 1.0 0.0 0.0 1.0 \n", "\n", " GSM4817154 GSM4817155 GSM4817156 GSM4817157 GSM4817158 \n", "Glioblastoma 1.0 1.0 1.0 1.0 1.0 \n", "Age 57.0 75.0 50.0 48.0 62.0 \n", "Gender 1.0 0.0 1.0 1.0 1.0 \n", "\n", "[3 rows x 34 columns]\n", "Linked data shape: (34, 20260)\n", "Linked data preview (first 5 rows, first 5 columns):\n", " Glioblastoma Age Gender A1BG A1BG-AS1\n", "GSM4817125 1.0 53.0 1.0 15.035213 7.521306\n", "GSM4817126 1.0 51.0 0.0 14.802535 7.346494\n", "GSM4817127 1.0 51.0 0.0 14.699763 7.377980\n", "GSM4817128 1.0 68.0 1.0 15.923379 7.710446\n", "GSM4817129 1.0 61.0 1.0 13.922135 6.784450\n", "\n", "Missing values before handling:\n", " Trait (Glioblastoma) missing: 0 out of 34\n", " Age missing: 0 out of 34\n", " Gender missing: 0 out of 34\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: (34, 20260)\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%: 51.0\n", " 50% (Median): 57.0\n", " 75%: 64.25\n", "Min: 11.0\n", "Max: 75.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 15 occurrences. This represents 44.12% 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. Normalize gene symbols using data from previous step\n", "# We already have gene_data from the previous step\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\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 clinical data\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", " # All samples are glioblastoma as per background info\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().upper()\n", " # Convert to binary: 0 for female, 1 for male\n", " if gender == 'F':\n", " return 0\n", " elif gender == 'M':\n", " return 1\n", " else:\n", " return None\n", " \n", "# Define row indices based on sample characteristics from step 1\n", "# We found these in the sample characteristics dictionary in step 1\n", "trait_row = 0 # All samples are brain tissue (glioblastoma)\n", "age_row = 2 # Age information is in row 2\n", "gender_row = 1 # Gender information is in row 1\n", "\n", "# Extract clinical features\n", "clinical_df = 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_df.to_csv(out_clinical_data_file)\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 }