{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "6b658bf4", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:08:55.332669Z", "iopub.status.busy": "2025-03-25T05:08:55.332566Z", "iopub.status.idle": "2025-03-25T05:08:55.526996Z", "shell.execute_reply": "2025-03-25T05:08:55.526640Z" } }, "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 = \"Epilepsy\"\n", "cohort = \"GSE143272\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Epilepsy\"\n", "in_cohort_dir = \"../../input/GEO/Epilepsy/GSE143272\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Epilepsy/GSE143272.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Epilepsy/gene_data/GSE143272.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Epilepsy/clinical_data/GSE143272.csv\"\n", "json_path = \"../../output/preprocess/Epilepsy/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "ac0b5eb9", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "d39ee122", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:08:55.528406Z", "iopub.status.busy": "2025-03-25T05:08:55.528260Z", "iopub.status.idle": "2025-03-25T05:08:55.664900Z", "shell.execute_reply": "2025-03-25T05:08:55.664580Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Peripheral blood expression profiles of patients with epilepsy receiving and not receiving antiepileptic drug monotherapy and their differential response to the treatment.\"\n", "!Series_summary\t\"The aim here was to identify mRNA expression biomarkers associated with the disease epilepsy and the antiepileptic drug response. Gene expression profiles of drug-naïve patients with epilepsy were compared with that of healthy controls. The profiles were significantly different between the two groups as well as patients with different epilepsy types i.e. idiopathic, symptomatic and cryptogenic. Besides, patients showing differential response to antiepileptic monotherapies were also having differential blood gene expression profiles.\"\n", "!Series_overall_design\t\"Total RNA obtained from peripheral blood samples of 34 drug-naïve patients with epilepsy and 57 followed-up patients showing differential response to antiepileptic drug monotherapy along with 50 healthy subjects as control group.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['age (in years): 26', 'age (in years): 28', 'age (in years): 29', 'age (in years): 32', 'age (in years): 27', 'age (in years): 22', 'age (in years): 16', 'age (in years): 14', 'age (in years): 25', 'age (in years): 20', 'age (in years): 18', 'age (in years): 24', 'age (in years): 40', 'age (in years): 21', 'age (in years): 38', 'age (in years): 23', 'age (in years): 48', 'age (in years): 34', 'age (in years): 10', 'age (in years): 35', 'age (in years): 15', 'age (in years): 17', 'age (in years): 44', 'age (in years): 19', 'age (in years): 42', 'age (in years): 36', 'age (in years): 45', 'age (in years): 30', 'age (in years): 37', 'age (in years): 31'], 1: ['Sex: Female', 'Sex: Male'], 2: ['epilepsy type: -', 'epilepsy type: Idiopathic', 'epilepsy type: Symptomatic', 'epilepsy type: Cryptogenic'], 3: ['treatment: -', 'treatment: Valproate', 'treatment: Drug-naïve', 'treatment: Carbamazepine', 'treatment: Phenytoin'], 4: ['drug response: -', 'drug response: Non-responder', 'drug response: Responder'], 5: ['ethnicity: North Indian']}\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": "1aa909aa", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "0a8933ff", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:08:55.666180Z", "iopub.status.busy": "2025-03-25T05:08:55.666060Z", "iopub.status.idle": "2025-03-25T05:08:55.684107Z", "shell.execute_reply": "2025-03-25T05:08:55.683801Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Preview of clinical data:\n", "{'GSM4255766': [0.0, 26.0, 0.0], 'GSM4255767': [1.0, 28.0, 1.0], 'GSM4255768': [0.0, 29.0, 1.0], 'GSM4255769': [0.0, 28.0, 1.0], 'GSM4255770': [1.0, 32.0, 1.0], 'GSM4255771': [1.0, 27.0, 0.0], 'GSM4255772': [0.0, 22.0, 0.0], 'GSM4255773': [1.0, 16.0, 1.0], 'GSM4255774': [1.0, 14.0, 0.0], 'GSM4255775': [0.0, 25.0, 0.0], 'GSM4255776': [0.0, 20.0, 1.0], 'GSM4255777': [1.0, 18.0, 0.0], 'GSM4255778': [1.0, 24.0, 1.0], 'GSM4255779': [0.0, 40.0, 0.0], 'GSM4255780': [0.0, 40.0, 1.0], 'GSM4255781': [1.0, 20.0, 0.0], 'GSM4255782': [0.0, 29.0, 0.0], 'GSM4255783': [1.0, 21.0, 0.0], 'GSM4255784': [1.0, 28.0, 1.0], 'GSM4255785': [1.0, 22.0, 1.0], 'GSM4255786': [0.0, 24.0, 0.0], 'GSM4255787': [0.0, 38.0, 0.0], 'GSM4255788': [1.0, 23.0, 1.0], 'GSM4255789': [0.0, 48.0, 1.0], 'GSM4255790': [0.0, 34.0, 0.0], 'GSM4255791': [1.0, 20.0, 1.0], 'GSM4255792': [1.0, 10.0, 1.0], 'GSM4255793': [0.0, 35.0, 1.0], 'GSM4255794': [1.0, 15.0, 1.0], 'GSM4255795': [1.0, 17.0, 1.0], 'GSM4255796': [0.0, 26.0, 1.0], 'GSM4255797': [0.0, 48.0, 1.0], 'GSM4255798': [1.0, 15.0, 1.0], 'GSM4255799': [1.0, 14.0, 0.0], 'GSM4255800': [0.0, 44.0, 1.0], 'GSM4255801': [1.0, 38.0, 1.0], 'GSM4255802': [1.0, 17.0, 0.0], 'GSM4255803': [1.0, 20.0, 1.0], 'GSM4255804': [0.0, 24.0, 0.0], 'GSM4255805': [1.0, 19.0, 1.0], 'GSM4255806': [1.0, 17.0, 1.0], 'GSM4255807': [0.0, 22.0, 0.0], 'GSM4255808': [0.0, 25.0, 1.0], 'GSM4255809': [1.0, 26.0, 1.0], 'GSM4255810': [1.0, 17.0, 0.0], 'GSM4255811': [0.0, 25.0, 0.0], 'GSM4255812': [1.0, 22.0, 0.0], 'GSM4255813': [1.0, 35.0, 1.0], 'GSM4255814': [1.0, 29.0, 1.0], 'GSM4255815': [1.0, 15.0, 0.0], 'GSM4255816': [1.0, 23.0, 0.0], 'GSM4255817': [0.0, 42.0, 0.0], 'GSM4255818': [1.0, 17.0, 0.0], 'GSM4255819': [1.0, 15.0, 0.0], 'GSM4255820': [1.0, 17.0, 0.0], 'GSM4255821': [0.0, 48.0, 1.0], 'GSM4255822': [1.0, 18.0, 1.0], 'GSM4255823': [1.0, 18.0, 0.0], 'GSM4255824': [1.0, 23.0, 1.0], 'GSM4255825': [1.0, 29.0, 1.0], 'GSM4255826': [0.0, 35.0, 0.0], 'GSM4255827': [1.0, 23.0, 1.0], 'GSM4255828': [1.0, 14.0, 0.0], 'GSM4255829': [1.0, 17.0, 1.0], 'GSM4255830': [1.0, 25.0, 1.0], 'GSM4255831': [1.0, 28.0, 0.0], 'GSM4255832': [1.0, 22.0, 1.0], 'GSM4255833': [1.0, 36.0, 0.0], 'GSM4255834': [1.0, 18.0, 1.0], 'GSM4255835': [0.0, 44.0, 1.0], 'GSM4255836': [1.0, 23.0, 0.0], 'GSM4255837': [1.0, 24.0, 1.0], 'GSM4255838': [0.0, 15.0, 1.0], 'GSM4255839': [1.0, 21.0, 0.0], 'GSM4255840': [1.0, 36.0, 1.0], 'GSM4255841': [0.0, 14.0, 0.0], 'GSM4255842': [1.0, 48.0, 0.0], 'GSM4255843': [1.0, 45.0, 0.0], 'GSM4255844': [0.0, 16.0, 1.0], 'GSM4255845': [1.0, 30.0, 0.0], 'GSM4255846': [1.0, 32.0, 1.0], 'GSM4255847': [1.0, 20.0, 0.0], 'GSM4255848': [1.0, 21.0, 0.0], 'GSM4255849': [1.0, 37.0, 1.0], 'GSM4255850': [1.0, 21.0, 0.0], 'GSM4255851': [1.0, 24.0, 1.0], 'GSM4255852': [0.0, 18.0, 1.0], 'GSM4255853': [1.0, 22.0, 1.0], 'GSM4255854': [1.0, 16.0, 1.0], 'GSM4255855': [0.0, 15.0, 0.0], 'GSM4255856': [1.0, 30.0, 1.0], 'GSM4255857': [0.0, 16.0, 0.0], 'GSM4255858': [1.0, 24.0, 1.0], 'GSM4255859': [1.0, 14.0, 0.0], 'GSM4255860': [1.0, 32.0, 1.0], 'GSM4255861': [0.0, 24.0, 1.0], 'GSM4255862': [1.0, 14.0, 0.0], 'GSM4255863': [1.0, 34.0, 1.0], 'GSM4255864': [0.0, 22.0, 0.0], 'GSM4255865': [1.0, 35.0, 0.0], 'GSM4255866': [1.0, 16.0, 0.0], 'GSM4255867': [0.0, 32.0, 1.0], 'GSM4255868': [1.0, 14.0, 0.0], 'GSM4255869': [1.0, 21.0, 1.0], 'GSM4255870': [0.0, 23.0, 0.0], 'GSM4255871': [1.0, 25.0, 0.0], 'GSM4255872': [1.0, 14.0, 1.0], 'GSM4255873': [0.0, 25.0, 1.0], 'GSM4255874': [1.0, 14.0, 1.0], 'GSM4255875': [0.0, 24.0, 1.0], 'GSM4255876': [0.0, 27.0, 1.0], 'GSM4255877': [1.0, 19.0, 1.0], 'GSM4255878': [1.0, 21.0, 1.0], 'GSM4255879': [0.0, 26.0, 0.0], 'GSM4255880': [1.0, 18.0, 1.0], 'GSM4255881': [1.0, 22.0, 1.0], 'GSM4255882': [1.0, 24.0, 1.0], 'GSM4255883': [1.0, 26.0, 0.0], 'GSM4255884': [0.0, 23.0, 0.0], 'GSM4255885': [0.0, 26.0, 1.0], 'GSM4255886': [0.0, 25.0, 1.0], 'GSM4255887': [0.0, 25.0, 1.0], 'GSM4255888': [0.0, 23.0, 0.0], 'GSM4255889': [0.0, 21.0, 1.0], 'GSM4255890': [0.0, 27.0, 0.0], 'GSM4255891': [0.0, 23.0, 1.0], 'GSM4255892': [0.0, 21.0, 0.0], 'GSM4255893': [0.0, 21.0, 0.0], 'GSM4255894': [0.0, 23.0, 1.0], 'GSM4255895': [0.0, 24.0, 0.0], 'GSM4255896': [1.0, 40.0, 1.0], 'GSM4255897': [1.0, 30.0, 1.0], 'GSM4255898': [1.0, 26.0, 0.0], 'GSM4255899': [1.0, 26.0, 1.0], 'GSM4255900': [1.0, 23.0, 0.0], 'GSM4255901': [1.0, 27.0, 1.0], 'GSM4255902': [1.0, 20.0, 1.0], 'GSM4255903': [1.0, 26.0, 0.0], 'GSM4255904': [1.0, 21.0, 0.0], 'GSM4255905': [1.0, 23.0, 1.0], 'GSM4255906': [1.0, 31.0, 1.0], 'GSM4255907': [1.0, 23.0, 1.0]}\n", "Clinical data saved to ../../output/preprocess/Epilepsy/clinical_data/GSE143272.csv\n" ] } ], "source": [ "# 1. Gene Expression Data Availability\n", "# Based on background information, this dataset appears to contain gene expression data\n", "# The series title and summary mention \"mRNA expression biomarkers\" and \"gene expression profiles\"\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "\n", "# Trait (Epilepsy):\n", "# From the sample characteristics, we can infer epilepsy status from rows 2 and 3 (epilepsy type and treatment)\n", "# We can consider someone as having epilepsy if they have an epilepsy type or are receiving treatment\n", "trait_row = 2 # Using epilepsy type as our indicator\n", "\n", "# Age:\n", "# Age is available in row 0\n", "age_row = 0\n", "\n", "# Gender:\n", "# Gender (Sex) is available in row 1\n", "gender_row = 1\n", "\n", "# 2.2 Data Type Conversion\n", "\n", "# Trait (Epilepsy):\n", "def convert_trait(value):\n", " # Extract the value after the colon\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # If epilepsy type is \"-\", this indicates a control subject without epilepsy\n", " if value == \"-\":\n", " return 0 # No epilepsy\n", " # If any type of epilepsy is mentioned, they have epilepsy\n", " elif value in [\"Idiopathic\", \"Symptomatic\", \"Cryptogenic\"]:\n", " return 1 # Has epilepsy\n", " else:\n", " return None # Unknown\n", "\n", "# Age:\n", "def convert_age(value):\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " try:\n", " return float(value) # Convert to numeric\n", " except:\n", " return None # Handle non-numeric or missing values\n", "\n", "# Gender:\n", "def convert_gender(value):\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " if value.lower() == 'female':\n", " return 0\n", " elif value.lower() == 'male':\n", " return 1\n", " else:\n", " return None # Unknown\n", "\n", "# 3. Save Metadata\n", "# Trait data availability is determined by whether trait_row is not None\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", "# Since trait_row is not None, we need to extract clinical features\n", "if trait_row is not None:\n", " 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 clinical dataframe\n", " preview = preview_df(clinical_df)\n", " print(\"Preview of clinical data:\")\n", " print(preview)\n", " \n", " # Save the clinical data\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " clinical_df.to_csv(out_clinical_data_file, index=False)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "0ad898af", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "74cdc417", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:08:55.685347Z", "iopub.status.busy": "2025-03-25T05:08:55.685140Z", "iopub.status.idle": "2025-03-25T05:08:55.911296Z", "shell.execute_reply": "2025-03-25T05:08:55.910836Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "SOFT file: ../../input/GEO/Epilepsy/GSE143272/GSE143272_family.soft.gz\n", "Matrix file: ../../input/GEO/Epilepsy/GSE143272/GSE143272_series_matrix.txt.gz\n", "Found the matrix table marker in the file.\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape: (13165, 142)\n", "First 20 gene/probe identifiers:\n", "['ILMN_1343291', 'ILMN_1343295', 'ILMN_1651228', 'ILMN_1651229', 'ILMN_1651254', 'ILMN_1651262', 'ILMN_1651278', 'ILMN_1651282', 'ILMN_1651296', 'ILMN_1651315', 'ILMN_1651316', 'ILMN_1651336', 'ILMN_1651346', 'ILMN_1651347', 'ILMN_1651364', 'ILMN_1651378', 'ILMN_1651385', 'ILMN_1651403', 'ILMN_1651405', 'ILMN_1651429']\n" ] } ], "source": [ "# 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", "print(f\"SOFT file: {soft_file}\")\n", "print(f\"Matrix file: {matrix_file}\")\n", "\n", "# Set gene availability flag\n", "is_gene_available = True # Initially assume gene data is available\n", "\n", "# First check if the matrix file contains the expected marker\n", "found_marker = False\n", "try:\n", " with gzip.open(matrix_file, 'rt') as file:\n", " for line in file:\n", " if \"!series_matrix_table_begin\" in line:\n", " found_marker = True\n", " break\n", " \n", " if found_marker:\n", " print(\"Found the matrix table marker in the file.\")\n", " else:\n", " print(\"Warning: Could not find '!series_matrix_table_begin' marker in the file.\")\n", " \n", " # Try to extract gene data from the matrix file\n", " gene_data = get_genetic_data(matrix_file)\n", " \n", " if gene_data.shape[0] == 0:\n", " print(\"Warning: Extracted gene data has 0 rows.\")\n", " is_gene_available = False\n", " else:\n", " print(f\"Gene data shape: {gene_data.shape}\")\n", " # Print the first 20 gene/probe identifiers\n", " print(\"First 20 gene/probe identifiers:\")\n", " print(gene_data.index[:20].tolist())\n", " \n", "except Exception as e:\n", " print(f\"Error extracting gene data: {e}\")\n", " is_gene_available = False\n", " \n", " # Try to diagnose the file format\n", " print(\"Examining file content to diagnose the issue:\")\n", " try:\n", " with gzip.open(matrix_file, 'rt') as file:\n", " for i, line in enumerate(file):\n", " if i < 10: # Print first 10 lines to diagnose\n", " print(f\"Line {i}: {line.strip()[:100]}...\") # Print first 100 chars of each line\n", " else:\n", " break\n", " except Exception as e2:\n", " print(f\"Error examining file: {e2}\")\n", "\n", "if not is_gene_available:\n", " print(\"Gene expression data could not be successfully extracted from this dataset.\")\n" ] }, { "cell_type": "markdown", "id": "e26d7bc9", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "a4f7b877", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:08:55.912537Z", "iopub.status.busy": "2025-03-25T05:08:55.912415Z", "iopub.status.idle": "2025-03-25T05:08:55.914316Z", "shell.execute_reply": "2025-03-25T05:08:55.914019Z" } }, "outputs": [], "source": [ "# Based on the gene identifiers starting with \"ILMN_\", these are Illumina microarray probe IDs\n", "# They are not human gene symbols and will need to be mapped to gene symbols\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "3e18d7f3", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "a510470f", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:08:55.915440Z", "iopub.status.busy": "2025-03-25T05:08:55.915331Z", "iopub.status.idle": "2025-03-25T05:09:00.880531Z", "shell.execute_reply": "2025-03-25T05:09:00.880186Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene annotation preview:\n", "Columns in gene annotation: ['ID', 'Species', 'Source', 'Search_Key', 'Transcript', 'ILMN_Gene', 'Source_Reference_ID', 'RefSeq_ID', 'Unigene_ID', 'Entrez_Gene_ID', 'GI', 'Accession', 'Symbol', 'Protein_Product', 'Probe_Id', 'Array_Address_Id', 'Probe_Type', 'Probe_Start', 'SEQUENCE', 'Chromosome', 'Probe_Chr_Orientation', 'Probe_Coordinates', 'Cytoband', 'Definition', 'Ontology_Component', 'Ontology_Process', 'Ontology_Function', 'Synonyms', 'Obsolete_Probe_Id', 'GB_ACC']\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.0, 6510136.0, 7560739.0, 1450438.0, 1240647.0], '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", "\n", "Sample of Symbol column (first 5 rows):\n", "Row 0: phage_lambda_genome\n", "Row 1: phage_lambda_genome\n", "Row 2: phage_lambda_genome:low\n", "Row 3: phage_lambda_genome:low\n", "Row 4: thrB\n", "\n", "Symbol column completeness: 44837/1917679 rows (2.34%)\n" ] } ], "source": [ "# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "gene_annotation = get_gene_annotation(soft_file)\n", "\n", "# 2. Analyze the gene annotation dataframe to identify which columns contain the gene identifiers and gene symbols\n", "print(\"\\nGene annotation preview:\")\n", "print(f\"Columns in gene annotation: {gene_annotation.columns.tolist()}\")\n", "print(preview_df(gene_annotation, n=5))\n", "\n", "# Based on the preview, 'ID' appears to be the probe ID and 'Symbol' contains gene names\n", "# Display more samples from the Symbol column to better understand the format\n", "print(\"\\nSample of Symbol column (first 5 rows):\")\n", "if 'Symbol' in gene_annotation.columns:\n", " for i in range(min(5, len(gene_annotation))):\n", " print(f\"Row {i}: {gene_annotation['Symbol'].iloc[i]}\")\n", "\n", "# Check the quality and completeness of the mapping\n", "if 'Symbol' in gene_annotation.columns:\n", " non_null_symbols = gene_annotation['Symbol'].notna().sum()\n", " total_rows = len(gene_annotation)\n", " print(f\"\\nSymbol column completeness: {non_null_symbols}/{total_rows} rows ({non_null_symbols/total_rows:.2%})\")\n" ] }, { "cell_type": "markdown", "id": "93e0298c", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "e0cddf53", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:09:00.882301Z", "iopub.status.busy": "2025-03-25T05:09:00.882147Z", "iopub.status.idle": "2025-03-25T05:09:01.868602Z", "shell.execute_reply": "2025-03-25T05:09:01.868212Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene mapping preview:\n", "{'ID': ['ILMN_1343048', 'ILMN_1343049', 'ILMN_1343050', 'ILMN_1343052', 'ILMN_1343059'], 'Gene': ['phage_lambda_genome', 'phage_lambda_genome', 'phage_lambda_genome:low', 'phage_lambda_genome:low', 'thrB']}\n", "Mapping dataframe shape: (44837, 2)\n", "\n", "Gene expression data after mapping:\n", "Shape: (9221, 142)\n", "First 5 gene symbols after mapping:\n", "['A2LD1', 'AADACL1', 'AAGAB', 'AAK1', 'AAMP']\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data saved to ../../output/preprocess/Epilepsy/gene_data/GSE143272.csv\n" ] } ], "source": [ "# 1. Identify the relevant columns in the gene annotation dataframe\n", "# From the preview, we can see:\n", "# - 'ID' column in the gene annotation contains the probe IDs (ILMN_*)\n", "# - 'Symbol' column contains the gene symbols\n", "\n", "# 2. Get a gene mapping dataframe by extracting the ID and Symbol columns\n", "mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Symbol')\n", "\n", "# Check the mapping dataframe\n", "print(\"\\nGene mapping preview:\")\n", "print(preview_df(mapping_df, n=5))\n", "print(f\"Mapping dataframe shape: {mapping_df.shape}\")\n", "\n", "# 3. Apply the gene mapping to convert probe-level data to gene expression data\n", "gene_data = apply_gene_mapping(gene_data, mapping_df)\n", "\n", "# Print information about the gene expression data\n", "print(\"\\nGene expression data after mapping:\")\n", "print(f\"Shape: {gene_data.shape}\")\n", "if gene_data.shape[0] > 0:\n", " print(\"First 5 gene symbols after mapping:\")\n", " print(gene_data.index[:5].tolist())\n", "\n", " # Save the gene expression data\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", "else:\n", " print(\"Warning: No gene symbols were mapped successfully.\")\n" ] }, { "cell_type": "markdown", "id": "557bf118", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "c14f3821", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:09:01.870395Z", "iopub.status.busy": "2025-03-25T05:09:01.870277Z", "iopub.status.idle": "2025-03-25T05:09:07.170703Z", "shell.execute_reply": "2025-03-25T05:09:07.170332Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape before normalization: (9221, 142)\n", "Gene data shape after normalization: (8978, 142)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data saved to ../../output/preprocess/Epilepsy/gene_data/GSE143272.csv\n", "Extracted clinical data shape: (3, 142)\n", "Preview of clinical data (first 5 samples):\n", " GSM4255766 GSM4255767 GSM4255768 GSM4255769 GSM4255770\n", "Epilepsy 0.0 1.0 0.0 0.0 1.0\n", "Age 26.0 28.0 29.0 28.0 32.0\n", "Gender 0.0 1.0 1.0 1.0 1.0\n", "Clinical data saved to ../../output/preprocess/Epilepsy/clinical_data/GSE143272.csv\n", "Gene data columns (first 5): ['GSM4255766', 'GSM4255767', 'GSM4255768', 'GSM4255769', 'GSM4255770']\n", "Clinical data columns (first 5): ['GSM4255766', 'GSM4255767', 'GSM4255768', 'GSM4255769', 'GSM4255770']\n", "Found 142 common samples between gene and clinical data\n", "Initial linked data shape: (142, 8981)\n", "Preview of linked data (first 5 rows, first 5 columns):\n", " Epilepsy Age Gender AAGAB AAK1\n", "GSM4255766 0.0 26.0 0.0 6.166417 5.549871\n", "GSM4255767 1.0 28.0 1.0 5.915127 5.434976\n", "GSM4255768 0.0 29.0 1.0 5.843318 5.401857\n", "GSM4255769 0.0 28.0 1.0 6.035075 5.708400\n", "GSM4255770 1.0 32.0 1.0 5.654042 5.795576\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data shape after handling missing values: (142, 8981)\n", "For the feature 'Epilepsy', the least common label is '0.0' with 51 occurrences. This represents 35.92% of the dataset.\n", "The distribution of the feature 'Epilepsy' in this dataset is fine.\n", "\n", "Quartiles for 'Age':\n", " 25%: 19.25\n", " 50% (Median): 23.0\n", " 75%: 28.0\n", "Min: 10.0\n", "Max: 48.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 62 occurrences. This represents 43.66% of the dataset.\n", "The distribution of the feature 'Gender' in this dataset is fine.\n", "\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data saved to ../../output/preprocess/Epilepsy/GSE143272.csv\n" ] } ], "source": [ "# 1. Normalize gene symbols in the gene expression data\n", "try:\n", " # Make sure the directory exists\n", " os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", " \n", " # Use the gene_data variable from the previous step (don't try to load it from file)\n", " print(f\"Gene data shape before normalization: {gene_data.shape}\")\n", " \n", " # Apply normalization to gene symbols\n", " normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", " print(f\"Gene data shape after normalization: {normalized_gene_data.shape}\")\n", " \n", " # Save the normalized gene data\n", " normalized_gene_data.to_csv(out_gene_data_file)\n", " print(f\"Normalized gene data saved to {out_gene_data_file}\")\n", " \n", " # Use the normalized data for further processing\n", " gene_data = normalized_gene_data\n", " is_gene_available = True\n", "except Exception as e:\n", " print(f\"Error normalizing gene data: {e}\")\n", " is_gene_available = False\n", "\n", "# 2. Load clinical data - respecting the analysis from Step 2\n", "# From Step 2, we determined:\n", "# trait_row = None # No Epilepsy data available\n", "# age_row = None\n", "# gender_row = None\n", "is_trait_available = trait_row is not None\n", "\n", "# Skip clinical feature extraction when trait_row is None\n", "if is_trait_available:\n", " try:\n", " # Load the clinical data from file\n", " soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", " background_info, clinical_data = get_background_and_clinical_data(matrix_file)\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", " gender_row=gender_row,\n", " convert_gender=convert_gender,\n", " age_row=age_row,\n", " convert_age=convert_age\n", " )\n", " \n", " print(f\"Extracted clinical data shape: {clinical_features.shape}\")\n", " print(\"Preview of clinical data (first 5 samples):\")\n", " print(clinical_features.iloc[:, :5])\n", " \n", " # Save the properly extracted clinical data\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 data saved to {out_clinical_data_file}\")\n", " except Exception as e:\n", " print(f\"Error extracting clinical data: {e}\")\n", " is_trait_available = False\n", "else:\n", " print(\"No trait data (Epilepsy) available in this dataset based on previous analysis.\")\n", "\n", "# 3. Link clinical and genetic data if both are available\n", "if is_trait_available and is_gene_available:\n", " try:\n", " # Debug the column names to ensure they match\n", " print(f\"Gene data columns (first 5): {gene_data.columns[:5].tolist()}\")\n", " print(f\"Clinical data columns (first 5): {clinical_features.columns[:5].tolist()}\")\n", " \n", " # Check for common sample IDs\n", " common_samples = set(gene_data.columns).intersection(clinical_features.columns)\n", " print(f\"Found {len(common_samples)} common samples between gene and clinical data\")\n", " \n", " if len(common_samples) > 0:\n", " # Link the clinical and genetic data\n", " linked_data = geo_link_clinical_genetic_data(clinical_features, gene_data)\n", " print(f\"Initial linked data shape: {linked_data.shape}\")\n", " \n", " # Debug the trait values before handling missing values\n", " print(\"Preview of linked data (first 5 rows, first 5 columns):\")\n", " print(linked_data.iloc[:5, :5])\n", " \n", " # Handle missing values\n", " linked_data = handle_missing_values(linked_data, trait)\n", " print(f\"Linked data shape after handling missing values: {linked_data.shape}\")\n", " \n", " if linked_data.shape[0] > 0:\n", " # Check for bias in trait and demographic features\n", " is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n", " \n", " # Validate the data quality and save cohort info\n", " note = \"Dataset contains gene expression data from GBM cell cultures, but no epilepsy phenotype information.\"\n", " is_usable = validate_and_save_cohort_info(\n", " is_final=True,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=is_gene_available,\n", " is_trait_available=is_trait_available,\n", " is_biased=is_biased,\n", " df=linked_data,\n", " note=note\n", " )\n", " \n", " # Save the linked data if it's usable\n", " if is_usable:\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " linked_data.to_csv(out_data_file)\n", " print(f\"Linked data saved to {out_data_file}\")\n", " else:\n", " print(\"Data not usable for the trait study - not saving final linked data.\")\n", " else:\n", " print(\"After handling missing values, no samples remain.\")\n", " validate_and_save_cohort_info(\n", " is_final=True,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=is_gene_available,\n", " is_trait_available=is_trait_available,\n", " is_biased=True,\n", " df=pd.DataFrame(),\n", " note=\"No valid samples after handling missing values.\"\n", " )\n", " else:\n", " print(\"No common samples found between gene expression and clinical data.\")\n", " validate_and_save_cohort_info(\n", " is_final=True,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=is_gene_available,\n", " is_trait_available=is_trait_available,\n", " is_biased=True,\n", " df=pd.DataFrame(),\n", " note=\"No common samples between gene expression and clinical data.\"\n", " )\n", " except Exception as e:\n", " print(f\"Error linking or processing data: {e}\")\n", " validate_and_save_cohort_info(\n", " is_final=True,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=is_gene_available,\n", " is_trait_available=is_trait_available,\n", " is_biased=True, # Assume biased if there's an error\n", " df=pd.DataFrame(), # Empty dataframe for metadata\n", " note=f\"Error in data processing: {str(e)}\"\n", " )\n", "else:\n", " # Create an empty DataFrame for metadata purposes\n", " empty_df = pd.DataFrame()\n", " \n", " # We can't proceed with linking if either trait or gene data is missing\n", " print(\"Cannot proceed with data linking due to missing trait or gene data.\")\n", " validate_and_save_cohort_info(\n", " is_final=True,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=is_gene_available,\n", " is_trait_available=is_trait_available,\n", " is_biased=True, # Data is unusable if we're missing components\n", " df=empty_df, # Empty dataframe for metadata\n", " note=\"Missing essential data components for linking: dataset contains gene expression data from GBM cell cultures, but no epilepsy phenotype information.\"\n", " )" ] } ], "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 }