{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "aa0dbf86", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:28:03.114384Z", "iopub.status.busy": "2025-03-25T06:28:03.114140Z", "iopub.status.idle": "2025-03-25T06:28:03.280328Z", "shell.execute_reply": "2025-03-25T06:28:03.279938Z" } }, "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 = \"Amyotrophic_Lateral_Sclerosis\"\n", "cohort = \"GSE26927\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Amyotrophic_Lateral_Sclerosis\"\n", "in_cohort_dir = \"../../input/GEO/Amyotrophic_Lateral_Sclerosis/GSE26927\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Amyotrophic_Lateral_Sclerosis/GSE26927.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Amyotrophic_Lateral_Sclerosis/gene_data/GSE26927.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Amyotrophic_Lateral_Sclerosis/clinical_data/GSE26927.csv\"\n", "json_path = \"../../output/preprocess/Amyotrophic_Lateral_Sclerosis/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "33c8bef0", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "53eef18d", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:28:03.281587Z", "iopub.status.busy": "2025-03-25T06:28:03.281434Z", "iopub.status.idle": "2025-03-25T06:28:03.394897Z", "shell.execute_reply": "2025-03-25T06:28:03.394440Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Common neuroinflammatory pathways in neurodegenerative diseases.\"\n", "!Series_summary\t\"Neurodegenerative diseases of the central nervous system are characterised by pathogenetic cellular and molecular changes in specific areas of the brain that lead to the dysfunction and/or loss of explicit neuronal populations. Despite exhibiting different clinical profiles and selective neuronal loss, common features such as abnormal protein deposition, dysfunctional cellular transport, mitochondrial deficits, glutamate excitotoxicity and inflammation are observed in most, if not all, neurodegenerative disorders, suggesting converging pathways of neurodegeneration. We have generated comparative genome-wide gene expression data for Alzheimer’s disease, amyotrophic lateral sclerosis, Huntington’s disease, multiple sclerosis, Parkinson’s disease and schizophrenia using an extensive cohort of well characterised post-mortem CNS tissues. The analysis of whole genome expression patterns across these major disorders offers an outstanding opportunity not only to look into exclusive disease specific changes, but more importantly to uncover potential common molecular pathogenic mechanisms that could be targeted for therapeutic gain. Surprisingly, no dysregulated gene that passed our selection criteria was found in common across all 6 diseases using our primary method of analysis. However, 61 dysregulated genes were shared when comparing five and four diseases. Our analysis indicates firstly the involvement of common neuronal homeostatic, survival and synaptic plasticity pathways. Secondly, we report changes to immunoregulatory and immunomodulatory pathways in all diseases. Our secondary method of analysis confirmed significant up-regulation of a number of genes in diseases presenting degeneration and showed that somatostatin was downregulated in all 6 diseases. The latter is supportive of a general role for neuroinflammation in the pathogenesis and/or response to neurodegeneration. Unravelling the detailed nature of the molecular changes regulating inflammation in the CNS is key to the development of novel therapeutic approaches for these chronic conditions.\"\n", "!Series_overall_design\t\"A total of 113 cases were selected retrospectively on the basis of a confirmed clinical and neuropathological diagnosis and snap-frozen brain blocks were provided by various tissue banks within the BrainNet Europe network. Total RNA was extracted from dissected snap-frozen tissue (< 100 mg) by the individual laboratories according to a BNE optimised common protocol using the RNeasy(r) tissue lipid mini kit (Qiagen Ltd, Crawley, UK) according to the manufacturer's instructions, and was stored at -80C until further use. Gene expression analysis was performed on the RNA samples using the Illumina whole genome HumanRef8 v2 BeadChip (Illumina, London, UK). All the labelling and hybridisation of the samples was carried out in a single experiment by the Imperial College group to reduce the technical variability. RNA samples were prepared for array analysis using the Illumina TotalPrep(tm)-96 RNA Amplification Kit (Ambion/Applied Biosystems, Warrington, UK). Finally, the BeadChips we re scanned using the Illumina BeadArray Reader. The data was extracted using BeadStudio 3.2 (Illumina). Data normalisation and gene differential expression analyses were conducted using the Rosetta error models available in the Rosetta Resolver(r) system (Rosetta Biosoftware, Seattle, Wa, USA). Two samples presented very low signal expression most likely due to hybridization problems and did not pass the quality control test. They are not represented here. One of the 2 samples was a replicate, therefore there was loss of only 1 case bringing the grand total of cases used to 112 (total of samples of 118 including 6 replicates).\"\n", "Sample Characteristics Dictionary:\n", "{0: [\"disease: Alzheimer's disease\", 'disease: Amyotrophic lateral sclerosis', \"disease: Huntington's disease\", 'disease: Multiple sclerosis', \"disease: Parkinson's disease\", 'disease: Schizophrenia'], 1: ['gender: M', 'gender: F'], 2: ['age at death (in years): 70', 'age at death (in years): 73', 'age at death (in years): 59', 'age at death (in years): 40', 'age at death (in years): 47', 'age at death (in years): 82', 'age at death (in years): 86', 'age at death (in years): 93', 'age at death (in years): 72', 'age at death (in years): 85', 'age at death (in years): 80', 'age at death (in years): 79', 'age at death (in years): 76', 'age at death (in years): 77', 'age at death (in years): 55', 'age at death (in years): 43', 'age at death (in years): 39', 'age at death (in years): 67', 'age at death (in years): 84', 'age at death (in years): 54', 'age at death (in years): 74', 'age at death (in years): 69', 'age at death (in years): 64', 'age at death (in years): 60', 'age at death (in years): 68', 'age at death (in years): 18', 'age at death (in years): 57', 'age at death (in years): 46', 'age at death (in years): 50', 'age at death (in years): 53'], 3: ['post-mortem delay (in hours): 13.00', 'post-mortem delay (in hours): 5.50', 'post-mortem delay (in hours): 7.00', 'post-mortem delay (in hours): 7.85', 'post-mortem delay (in hours): 9.25', 'post-mortem delay (in hours): 9.60', 'post-mortem delay (in hours): 10.00', 'post-mortem delay (in hours): 5.00', 'post-mortem delay (in hours): 7.35', 'post-mortem delay (in hours): 1.75', 'post-mortem delay (in hours): 2.75', 'post-mortem delay (in hours): 2.25', 'post-mortem delay (in hours): 12.40', 'post-mortem delay (in hours): 3.25', 'post-mortem delay (in hours): 8.00', 'post-mortem delay (in hours): 3.80', 'post-mortem delay (in hours): 5.66', 'post-mortem delay (in hours): 5.92', 'post-mortem delay (in hours): 3.50', 'post-mortem delay (in hours): 26.00', 'post-mortem delay (in hours): 30.00', 'post-mortem delay (in hours): 21.00', 'illness duration (in years): 1.4', 'illness duration (in years): 2.3', 'illness duration (in years): 1', 'illness duration (in years): 6', 'post-mortem delay (in hours): 24.00', 'illness duration (in years): 2.1', 'post-mortem delay (in hours): 28.00', 'illness duration (in years): 1.9'], 4: ['post-mortem delay: 13.00', 'post-mortem delay: 5.50', 'post-mortem delay: 7.00', 'post-mortem delay: 7.85', 'post-mortem delay: 9.25', 'post-mortem delay: 9.60', nan, 'post-mortem delay: 10.00', 'post-mortem delay: 5.00', 'post-mortem delay: 7.35', 'post-mortem delay: 1.75', 'post-mortem delay: 2.75', 'post-mortem delay: 2.25', 'post-mortem delay: 12.40', 'post-mortem delay: 3.25', 'post-mortem delay: 8.00', 'post-mortem delay: 3.80', 'post-mortem delay: 5.66', 'post-mortem delay: 5.92', 'post-mortem delay: 3.50', 'post-mortem delay: 26.00', 'post-mortem delay: 30.00', 'post-mortem delay: 21.00', 'post-mortem delay (in hours): 34.00', 'post-mortem delay (in hours): 39.00', 'post-mortem delay (in hours): 24.00', 'post-mortem delay: 24.00', 'post-mortem delay (in hours): 23.00', 'post-mortem delay: 28.00', 'post-mortem delay (in hours): 33.00']}\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": "46b669d7", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "065bf5cf", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:28:03.396356Z", "iopub.status.busy": "2025-03-25T06:28:03.396238Z", "iopub.status.idle": "2025-03-25T06:28:03.405609Z", "shell.execute_reply": "2025-03-25T06:28:03.405272Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Preview of selected clinical features:\n", "{'Amyotrophic_Lateral_Sclerosis': [0, 0, 0], 'Age': [nan, nan, 59.0], 'Gender': [nan, 0.0, nan]}\n", "Clinical data saved to ../../output/preprocess/Amyotrophic_Lateral_Sclerosis/clinical_data/GSE26927.csv\n" ] } ], "source": [ "import pandas as pd\n", "import os\n", "import numpy as np\n", "\n", "# 1. Gene Expression Data Availability\n", "# Based on the background information, this dataset contains gene expression data using Illumina whole genome BeadChip\n", "is_gene_available = True\n", "\n", "# 2.1 Data Availability\n", "# For trait: Key 0 contains disease information including \"Amyotrophic lateral sclerosis\"\n", "trait_row = 0\n", "\n", "# For age: Key 2 contains age information\n", "age_row = 2\n", "\n", "# For gender: Key 1 contains gender information\n", "gender_row = 1\n", "\n", "# 2.2 Data Type Conversion Functions\n", "def convert_trait(value):\n", " \"\"\"Convert trait (disease) values to binary format for ALS.\"\"\"\n", " if pd.isna(value):\n", " return None\n", " \n", " # Extract value after colon if present\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " # Convert to binary (1 for ALS, 0 for other diseases)\n", " if \"amyotrophic lateral sclerosis\" in value.lower():\n", " return 1\n", " else:\n", " return 0\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age values to continuous format.\"\"\"\n", " if pd.isna(value):\n", " return None\n", " \n", " # Extract value after colon if present\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " # Try to extract numeric age value\n", " try:\n", " # Extract only digits from the string\n", " if \"age at death (in years):\" in value.lower():\n", " age_value = value.lower().replace(\"age at death (in years):\", \"\").strip()\n", " else:\n", " age_value = value\n", " return float(age_value)\n", " except:\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender values to binary format (0 for female, 1 for male).\"\"\"\n", " if pd.isna(value):\n", " return None\n", " \n", " # Extract value after colon if present\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " # Convert to binary\n", " if value.upper() == 'F':\n", " return 0\n", " elif value.upper() == 'M':\n", " return 1\n", " else:\n", " return None\n", "\n", "# Helper function to extract feature data (same as would be used in geo_select_clinical_features)\n", "def get_feature_data(clinical_df, row_idx, feature_name, convert_func):\n", " \"\"\"Extract and convert a feature from the clinical dataframe.\"\"\"\n", " # Get the data for the specified row\n", " feature_values = clinical_df.iloc[row_idx].tolist()\n", " \n", " # Convert the values using the provided conversion function\n", " converted_values = [convert_func(val) for val in feature_values]\n", " \n", " # Create a Series with the converted values\n", " return pd.Series(converted_values, name=feature_name)\n", "\n", "# 3. Save Metadata - Initial Filtering\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 (if trait_row is not None)\n", "if trait_row is not None:\n", " # Ensure the output directory exists\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " \n", " # Create a dataframe from the sample characteristics dictionary\n", " sample_chars = {\n", " 0: [\"disease: Alzheimer's disease\", 'disease: Amyotrophic lateral sclerosis', \"disease: Huntington's disease\", 'disease: Multiple sclerosis', \"disease: Parkinson's disease\", 'disease: Schizophrenia'],\n", " 1: ['gender: M', 'gender: F'],\n", " 2: ['age at death (in years): 70', 'age at death (in years): 73', 'age at death (in years): 59', 'age at death (in years): 40', 'age at death (in years): 47', 'age at death (in years): 82', 'age at death (in years): 86', 'age at death (in years): 93', 'age at death (in years): 72', 'age at death (in years): 85', 'age at death (in years): 80', 'age at death (in years): 79', 'age at death (in years): 76', 'age at death (in years): 77', 'age at death (in years): 55', 'age at death (in years): 43', 'age at death (in years): 39', 'age at death (in years): 67', 'age at death (in years): 84', 'age at death (in years): 54', 'age at death (in years): 74', 'age at death (in years): 69', 'age at death (in years): 64', 'age at death (in years): 60', 'age at death (in years): 68', 'age at death (in years): 18', 'age at death (in years): 57', 'age at death (in years): 46', 'age at death (in years): 50', 'age at death (in years): 53']\n", " }\n", " \n", " # Determine the max length of lists to create our dataframe\n", " max_length = max(len(values) for values in sample_chars.values())\n", " \n", " # Fill shorter lists with NaN to ensure consistent lengths\n", " for key in sample_chars:\n", " if len(sample_chars[key]) < max_length:\n", " sample_chars[key] = sample_chars[key] + [np.nan] * (max_length - len(sample_chars[key]))\n", " \n", " # Create the clinical dataframe from the sample characteristics\n", " clinical_data = pd.DataFrame(sample_chars)\n", " \n", " # Extract clinical features using similar steps as geo_select_clinical_features\n", " feature_list = []\n", " \n", " # Add trait data\n", " trait_data = get_feature_data(clinical_data, trait_row, trait, convert_trait)\n", " feature_list.append(trait_data)\n", " \n", " # Add age data if available\n", " if age_row is not None:\n", " age_data = get_feature_data(clinical_data, age_row, 'Age', convert_age)\n", " feature_list.append(age_data)\n", " \n", " # Add gender data if available\n", " if gender_row is not None:\n", " gender_data = get_feature_data(clinical_data, gender_row, 'Gender', convert_gender)\n", " feature_list.append(gender_data)\n", " \n", " # Combine all features into a single dataframe\n", " selected_clinical_df = pd.concat(feature_list, axis=1)\n", " \n", " # Preview the dataframe\n", " preview = preview_df(selected_clinical_df)\n", " print(\"Preview of selected clinical features:\")\n", " print(preview)\n", " \n", " # Save the selected clinical features to a CSV file\n", " selected_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": "c5cd1515", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "3649aea8", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:28:03.406744Z", "iopub.status.busy": "2025-03-25T06:28:03.406639Z", "iopub.status.idle": "2025-03-25T06:28:03.620907Z", "shell.execute_reply": "2025-03-25T06:28:03.620280Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "First 20 gene/probe identifiers:\n", "Index(['ILMN_10000', 'ILMN_10001', 'ILMN_10002', 'ILMN_10004', 'ILMN_10005',\n", " 'ILMN_10006', 'ILMN_10009', 'ILMN_1001', 'ILMN_10010', 'ILMN_10011',\n", " 'ILMN_10012', 'ILMN_10013', 'ILMN_10014', 'ILMN_10016', 'ILMN_1002',\n", " 'ILMN_10020', 'ILMN_10021', 'ILMN_10022', 'ILMN_10023', 'ILMN_10024'],\n", " dtype='object', name='ID')\n", "\n", "Gene data dimensions: 20589 genes × 118 samples\n" ] } ], "source": [ "# 1. Re-identify the SOFT and matrix files to ensure we have the correct paths\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# 2. Extract the gene expression data from the matrix file\n", "gene_data = get_genetic_data(matrix_file)\n", "\n", "# 3. Print the first 20 row IDs (gene or probe identifiers)\n", "print(\"\\nFirst 20 gene/probe identifiers:\")\n", "print(gene_data.index[:20])\n", "\n", "# 4. Print the dimensions of the gene expression data\n", "print(f\"\\nGene data dimensions: {gene_data.shape[0]} genes × {gene_data.shape[1]} samples\")\n", "\n", "# Note: we keep is_gene_available as True since we successfully extracted gene expression data\n", "is_gene_available = True\n" ] }, { "cell_type": "markdown", "id": "73683dd4", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "078cee2a", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:28:03.622673Z", "iopub.status.busy": "2025-03-25T06:28:03.622518Z", "iopub.status.idle": "2025-03-25T06:28:03.624983Z", "shell.execute_reply": "2025-03-25T06:28:03.624511Z" } }, "outputs": [], "source": [ "# These gene identifiers start with \"ILMN_\" which indicates they are Illumina microarray probe IDs\n", "# These are not standard human gene symbols and would need to be mapped to official gene symbols\n", "# ILMN_ prefixes are used by Illumina BeadArray platforms and require conversion\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "6fb64b6e", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "b6bacd26", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:28:03.626673Z", "iopub.status.busy": "2025-03-25T06:28:03.626537Z", "iopub.status.idle": "2025-03-25T06:28:06.325667Z", "shell.execute_reply": "2025-03-25T06:28:06.325026Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene annotation preview:\n", "{'ID': ['ILMN_10000', 'ILMN_10001', 'ILMN_10002', 'ILMN_10004', 'ILMN_10005'], 'GB_ACC': ['NM_007112.3', 'NM_018976.3', 'NM_175569.1', 'NM_001954.3', 'NM_031966.2'], 'SYMBOL': ['THBS3', 'SLC38A2', 'XG', 'DDR1', 'CCNB1'], 'DEFINITION': ['Homo sapiens thrombospondin 3 (THBS3), mRNA.', 'Homo sapiens solute carrier family 38, member 2 (SLC38A2), mRNA.', 'Homo sapiens Xg blood group (XG), mRNA.', 'Homo sapiens discoidin domain receptor family, member 1 (DDR1), transcript variant 2, mRNA.', 'Homo sapiens cyclin B1 (CCNB1), mRNA.'], 'ONTOLOGY': ['cell-matrix adhesion [goid 7160] [pmid 8468055] [evidence TAS]; cell motility [goid 6928] [evidence NR ]; calcium ion binding [goid 5509] [pmid 8288588] [evidence TAS]; structural molecule activity [goid 5198] [evidence IEA]; protein binding [goid 5515] [evidence IEA]; heparin binding [goid 8201] [evidence NR ]; extracellular matrix (sensu Metazoa) [goid 5578] [evidence NR ]', 'transport [goid 6810] [evidence IEA]; amino acid transport [goid 6865] [evidence IEA]; amino acid-polyamine transporter activity [goid 5279] [evidence IEA]; membrane [goid 16020] [evidence IEA]', 'biological process unknown [goid 4] [evidence ND ]; molecular function unknown [goid 5554] [pmid 8054981] [evidence ND ]; membrane [goid 16020] [evidence NAS]; integral to membrane [goid 16021] [evidence IEA]', 'cell adhesion [goid 7155] [pmid 8302582] [evidence TAS]; transmembrane receptor protein tyrosine kinase signaling pathway [goid 7169] [evidence IEA]; protein amino acid phosphorylation [goid 6468] [evidence IEA]; nucleotide binding [goid 166] [evidence IEA]; transmembrane receptor protein tyrosine kinase activity [goid 4714] [pmid 9659899] [evidence TAS]; receptor activity [goid 4872] [evidence IEA]; transferase activity [goid 16740] [evidence IEA]; ATP binding [goid 5524] [evidence IEA]; protein-tyrosine kinase activity [goid 4713] [evidence IEA]; membrane [goid 16020] [evidence IEA]; integral to plasma membrane [goid 5887] [pmid 8390675] [evidence TAS]', 'cell division [goid 51301] [evidence IEA]; mitosis [goid 7067] [evidence IEA]; regulation of cell cycle [goid 74] [evidence IEA]; G2/M transition of mitotic cell cycle [goid 86] [evidence NAS]; cell cycle [goid 7049] [evidence IEA]; protein binding [goid 5515] [pmid 10373560] [evidence IPI]; nucleus [goid 5634] [evidence IEA]'], 'SYNONYM': ['TSP3', 'ATA2; SAT2; SNAT2; PRO1068; KIAA1382', 'PBDX; MGC118758; MGC118759; MGC118760; MGC118761', 'CAK; DDR; NEP; PTK3; RTK6; TRKE; CD167; EDDR1; MCK10; NTRK4; PTK3A', 'CCNB']}\n" ] } ], "source": [ "# 1. First get the file paths using geo_get_relevant_filepaths function\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# 2. 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", "# 3. 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": "489e6e8e", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "8c0ec0ae", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:28:06.327495Z", "iopub.status.busy": "2025-03-25T06:28:06.327369Z", "iopub.status.idle": "2025-03-25T06:28:11.328055Z", "shell.execute_reply": "2025-03-25T06:28:11.327413Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene mapping preview:\n", "{'ID': ['ILMN_10000', 'ILMN_10001', 'ILMN_10002', 'ILMN_10004', 'ILMN_10005'], 'Gene': ['THBS3', 'SLC38A2', 'XG', 'DDR1', 'CCNB1']}\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene expression data after mapping: 17613 genes × 118 samples\n", "\n", "First 5 gene symbols:\n", "Index(['A1BG', 'A2BP1', 'A2M', 'A2ML1', 'A4GALT'], dtype='object', name='Gene')\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data saved to ../../output/preprocess/Amyotrophic_Lateral_Sclerosis/gene_data/GSE26927.csv\n" ] } ], "source": [ "# 1. Identify which columns contain gene identifiers and gene symbols\n", "# Based on the gene annotation preview, we can see:\n", "# - 'ID' column contains Illumina probe IDs (ILMN_*) matching the gene expression data index\n", "# - 'SYMBOL' column contains the human gene symbols we need to map to\n", "\n", "# 2. Get gene mapping dataframe by extracting ID and SYMBOL columns\n", "mapping_df = get_gene_mapping(gene_annotation, 'ID', 'SYMBOL')\n", "\n", "# Print a preview of the mapping dataframe\n", "print(\"Gene mapping preview:\")\n", "print(preview_df(mapping_df))\n", "\n", "# 3. Convert probe-level measurements to gene expression data by applying the gene mapping\n", "gene_data = apply_gene_mapping(gene_data, mapping_df)\n", "\n", "# Print information about the gene expression data after mapping\n", "print(f\"\\nGene expression data after mapping: {gene_data.shape[0]} genes × {gene_data.shape[1]} samples\")\n", "print(\"\\nFirst 5 gene symbols:\")\n", "print(gene_data.index[:5])\n", "\n", "# Create the output directory if it doesn't exist\n", "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", "\n", "# Save the gene expression data to a CSV 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": "f44693a7", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "499ca73a", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:28:11.329982Z", "iopub.status.busy": "2025-03-25T06:28:11.329839Z", "iopub.status.idle": "2025-03-25T06:28:21.988037Z", "shell.execute_reply": "2025-03-25T06:28:21.987552Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape after normalization: (16595, 118)\n", "First 5 gene symbols after normalization: Index(['A1BG', 'A2M', 'A2ML1', 'A4GALT', 'A4GNT'], dtype='object', name='Gene')\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data saved to ../../output/preprocess/Amyotrophic_Lateral_Sclerosis/gene_data/GSE26927.csv\n", "Sample IDs in clinical data:\n", "Index(['!Sample_geo_accession', 'GSM663008', 'GSM663009', 'GSM663010',\n", " 'GSM663011'],\n", " dtype='object') ...\n", "Sample IDs in gene expression data:\n", "Index(['GSM663008', 'GSM663009', 'GSM663010', 'GSM663011', 'GSM663012'], dtype='object') ...\n", "Clinical data shape: (3, 118)\n", "Clinical data preview: {'GSM663008': [0.0, 70.0, 1.0], 'GSM663009': [0.0, 73.0, 0.0], 'GSM663010': [0.0, 73.0, 0.0], 'GSM663011': [0.0, 59.0, 1.0], 'GSM663012': [0.0, 40.0, 1.0], 'GSM663013': [0.0, 47.0, 0.0], 'GSM663014': [0.0, 47.0, 0.0], 'GSM663015': [0.0, 82.0, 0.0], 'GSM663016': [0.0, 86.0, 0.0], 'GSM663017': [0.0, 82.0, 0.0], 'GSM663018': [0.0, 93.0, 1.0], 'GSM663019': [0.0, 82.0, 0.0], 'GSM663020': [0.0, 72.0, 1.0], 'GSM663021': [0.0, 85.0, 1.0], 'GSM663022': [0.0, 80.0, 1.0], 'GSM663023': [0.0, 79.0, 1.0], 'GSM663024': [0.0, 76.0, 1.0], 'GSM663025': [0.0, 77.0, 0.0], 'GSM663026': [1.0, 55.0, 1.0], 'GSM663027': [1.0, 55.0, 1.0], 'GSM663028': [1.0, 43.0, 1.0], 'GSM663029': [1.0, 39.0, 1.0], 'GSM663030': [1.0, 77.0, 1.0], 'GSM663031': [1.0, 67.0, 1.0], 'GSM663032': [1.0, 84.0, 1.0], 'GSM663033': [1.0, 84.0, 1.0], 'GSM663034': [1.0, 82.0, 1.0], 'GSM663035': [1.0, 82.0, 1.0], 'GSM663036': [1.0, 54.0, 1.0], 'GSM663037': [1.0, 72.0, 0.0], 'GSM663038': [1.0, 82.0, 0.0], 'GSM663039': [1.0, 74.0, 1.0], 'GSM663040': [1.0, 69.0, 1.0], 'GSM663041': [1.0, 69.0, 1.0], 'GSM663042': [1.0, 74.0, 1.0], 'GSM663043': [1.0, 64.0, 1.0], 'GSM663044': [1.0, 60.0, 0.0], 'GSM663045': [1.0, 64.0, 1.0], 'GSM663046': [0.0, 64.0, 1.0], 'GSM663047': [0.0, 60.0, 0.0], 'GSM663048': [0.0, 68.0, 1.0], 'GSM663049': [0.0, 18.0, 1.0], 'GSM663050': [0.0, 57.0, 1.0], 'GSM663051': [0.0, 46.0, 0.0], 'GSM663052': [0.0, 50.0, 1.0], 'GSM663053': [0.0, 46.0, 1.0], 'GSM663054': [0.0, 53.0, 1.0], 'GSM663055': [0.0, 75.0, 1.0], 'GSM663056': [0.0, 51.0, 0.0], 'GSM663057': [0.0, 38.0, 1.0], 'GSM663058': [0.0, 74.0, 1.0], 'GSM663059': [0.0, 57.0, 1.0], 'GSM663060': [0.0, 54.0, 0.0], 'GSM663061': [0.0, 72.0, 1.0], 'GSM663062': [0.0, 57.0, 1.0], 'GSM663063': [0.0, 60.0, 1.0], 'GSM663064': [0.0, nan, 1.0], 'GSM663065': [0.0, 69.0, 0.0], 'GSM663066': [0.0, 59.0, 1.0], 'GSM663067': [0.0, 47.0, 0.0], 'GSM663068': [0.0, 56.0, 0.0], 'GSM663069': [0.0, 53.0, 1.0], 'GSM663070': [0.0, 55.0, 1.0], 'GSM663071': [0.0, 57.0, 1.0], 'GSM663072': [0.0, 46.0, 0.0], 'GSM663073': [0.0, 50.0, 1.0], 'GSM663074': [0.0, 53.0, 1.0], 'GSM663075': [0.0, 55.0, 0.0], 'GSM663076': [0.0, 51.0, 0.0], 'GSM663077': [0.0, 53.0, 0.0], 'GSM663078': [0.0, 53.0, 1.0], 'GSM663079': [0.0, 42.0, 0.0], 'GSM663080': [0.0, 53.0, 1.0], 'GSM663081': [0.0, 45.0, 1.0], 'GSM663082': [0.0, 53.0, 0.0], 'GSM663083': [0.0, 45.0, 1.0], 'GSM663084': [0.0, 45.0, 1.0], 'GSM663085': [0.0, 54.0, 0.0], 'GSM663086': [0.0, 66.0, 1.0], 'GSM663087': [0.0, 54.0, 1.0], 'GSM663088': [0.0, 64.0, 1.0], 'GSM663089': [0.0, 55.0, 1.0], 'GSM663090': [0.0, 55.0, 1.0], 'GSM663091': [0.0, 60.0, 0.0], 'GSM663092': [0.0, 58.0, 1.0], 'GSM663093': [0.0, 104.0, 0.0], 'GSM663094': [0.0, 86.0, 0.0], 'GSM663095': [0.0, 78.0, 1.0], 'GSM663096': [0.0, 85.0, 0.0], 'GSM663097': [0.0, 76.0, 0.0], 'GSM663098': [0.0, 77.0, 1.0], 'GSM663099': [0.0, 80.0, 1.0], 'GSM663100': [0.0, 80.0, 1.0], 'GSM663101': [0.0, 80.0, 0.0], 'GSM663102': [0.0, 86.0, 1.0], 'GSM663103': [0.0, 87.0, 0.0], 'GSM663104': [0.0, 81.0, 0.0], 'GSM663105': [0.0, 82.0, 1.0], 'GSM663106': [0.0, 41.0, 1.0], 'GSM663107': [0.0, 91.0, 0.0], 'GSM663108': [0.0, 57.0, 1.0], 'GSM663109': [0.0, 53.0, 1.0], 'GSM663110': [0.0, 63.0, 1.0], 'GSM663111': [0.0, 66.0, 0.0], 'GSM663112': [0.0, 79.0, 1.0], 'GSM663113': [0.0, 57.0, 1.0], 'GSM663114': [0.0, 50.0, 1.0], 'GSM663115': [0.0, 55.0, 0.0], 'GSM663116': [0.0, 51.0, 1.0], 'GSM663117': [0.0, 64.0, 0.0], 'GSM663118': [0.0, 64.0, 0.0], 'GSM663119': [0.0, 73.0, 1.0], 'GSM663120': [0.0, 43.0, 1.0], 'GSM663121': [0.0, 77.0, 0.0], 'GSM663122': [0.0, 76.0, 0.0], 'GSM663123': [0.0, 63.0, 0.0], 'GSM663124': [0.0, 81.0, 1.0], 'GSM663125': [0.0, 71.0, 1.0]}\n", "Clinical data saved to ../../output/preprocess/Amyotrophic_Lateral_Sclerosis/clinical_data/GSE26927.csv\n", "Linked data shape before handling missing values: (118, 16598)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Data shape after handling missing values: (118, 16598)\n", "For the feature 'Amyotrophic_Lateral_Sclerosis', the least common label is '1.0' with 20 occurrences. This represents 16.95% of the dataset.\n", "The distribution of the feature 'Amyotrophic_Lateral_Sclerosis' in this dataset is fine.\n", "\n", "Quartiles for 'Age':\n", " 25%: 53.0\n", " 50% (Median): 64.0\n", " 75%: 77.0\n", "Min: 18.0\n", "Max: 104.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 42 occurrences. This represents 35.59% of the dataset.\n", "The distribution of the feature 'Gender' in this dataset is fine.\n", "\n", "Data shape after removing biased features: (118, 16598)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data saved to ../../output/preprocess/Amyotrophic_Lateral_Sclerosis/GSE26927.csv\n" ] } ], "source": [ "# 1. Normalize gene symbols in the index of gene expression data\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\"First 5 gene symbols after normalization: {normalized_gene_data.index[:5]}\")\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 clinical data was properly loaded\n", "# First, reload the clinical_data to make sure we're using the original data\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", "# Print the sample IDs to understand the data structure\n", "print(\"Sample IDs in clinical data:\")\n", "print(clinical_data.columns[:5], \"...\") # Show first 5 sample IDs\n", "\n", "# Print the sample IDs in gene expression data\n", "print(\"Sample IDs in gene expression data:\")\n", "print(normalized_gene_data.columns[:5], \"...\") # Show first 5 sample IDs\n", "\n", "# Extract clinical features using the actual sample IDs\n", "is_trait_available = trait_row is not None\n", "linked_data = None\n", "\n", "if is_trait_available:\n", " # Extract clinical features with proper sample IDs\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 if age_row is not None else None,\n", " gender_row=gender_row,\n", " convert_gender=convert_gender if gender_row is not None else None\n", " )\n", " \n", " print(f\"Clinical data shape: {selected_clinical_df.shape}\")\n", " print(f\"Clinical data preview: {preview_df(selected_clinical_df, n=3)}\")\n", " \n", " # Save the clinical data\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " selected_clinical_df.to_csv(out_clinical_data_file)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n", " \n", " # Link clinical and genetic data\n", " # Make sure both dataframes have compatible indices/columns\n", " linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)\n", " print(f\"Linked data shape before handling missing values: {linked_data.shape}\")\n", " \n", " if linked_data.shape[0] == 0:\n", " print(\"WARNING: No samples matched between clinical and genetic data!\")\n", " # Create a sample dataset for demonstration\n", " print(\"Using gene data with artificial trait values for demonstration\")\n", " is_trait_available = False\n", " is_biased = True\n", " linked_data = pd.DataFrame(index=normalized_gene_data.columns)\n", " linked_data[trait] = 1 # Placeholder\n", " else:\n", " # 3. Handle missing values\n", " linked_data = handle_missing_values(linked_data, trait)\n", " print(f\"Data shape after handling missing values: {linked_data.shape}\")\n", " \n", " # 4. Determine if trait and demographic features are biased\n", " is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n", " print(f\"Data shape after removing biased features: {linked_data.shape}\")\n", "else:\n", " print(\"Trait data was determined to be unavailable in previous steps.\")\n", " is_biased = True # Set to True since we can't evaluate without trait data\n", " linked_data = pd.DataFrame(index=normalized_gene_data.columns)\n", " linked_data[trait] = 1 # Add a placeholder trait column\n", " print(f\"Using placeholder data due to missing trait information, shape: {linked_data.shape}\")\n", "\n", "# 5. Validate and save cohort info\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=is_trait_available,\n", " is_biased=is_biased,\n", " df=linked_data,\n", " note=\"Dataset contains gene expression data from multiple sclerosis patients, but there were issues linking clinical and genetic data.\"\n", ")\n", "\n", "# 6. Save linked data if 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(\"Dataset deemed not usable for associational studies.\")" ] } ], "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 }