{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "86897626", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:27:50.526912Z", "iopub.status.busy": "2025-03-25T06:27:50.526798Z", "iopub.status.idle": "2025-03-25T06:27:50.683855Z", "shell.execute_reply": "2025-03-25T06:27:50.683402Z" } }, "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 = \"GSE139384\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Amyotrophic_Lateral_Sclerosis\"\n", "in_cohort_dir = \"../../input/GEO/Amyotrophic_Lateral_Sclerosis/GSE139384\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Amyotrophic_Lateral_Sclerosis/GSE139384.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Amyotrophic_Lateral_Sclerosis/gene_data/GSE139384.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Amyotrophic_Lateral_Sclerosis/clinical_data/GSE139384.csv\"\n", "json_path = \"../../output/preprocess/Amyotrophic_Lateral_Sclerosis/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "e2eebe8c", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "f886f754", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:27:50.685116Z", "iopub.status.busy": "2025-03-25T06:27:50.684959Z", "iopub.status.idle": "2025-03-25T06:27:50.722160Z", "shell.execute_reply": "2025-03-25T06:27:50.721758Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Synaptopathy in Kii ALS/PDC, a disease concept based on transcriptome analyses of human brains\"\n", "!Series_summary\t\"Amyotrophic lateral sclerosis (ALS) and parkinsonism-dementia complex (PDC) (ALS/PDC) is a unique endemic neurodegenerative disease, with high-incidence foci in the Kii Peninsula, Japan. Although ALS/PDC presents with multiple proteinopathies, the genetic and environmental factors that influence disease onset remain unknown. We performed transcriptome analyses of patients’ brains, which may provide new insights into the pathomechanisms underlying Kii ALS/PDC.\"\n", "!Series_summary\t\"We prepared frozen brains from 3 healthy controls (frontal lobe and temporal lobe), 3 patients with Alzheimer’s disease (AD) (frontal lobe and temporal lobe) as tauopathy-disease controls, and 21 patients with Kii ALS/PDC (frontal lobe and/or temporal lobe). We acquired microarray data from the cerebral gray and white matter tissues of Kii ALS/PDC patients.\"\n", "!Series_summary\t\"Microarray data revealed that the expression levels of genes associated with neurons, heat shock proteins (Hsps), DNA binding/damage, and senescence were significantly changed in Kii ALS/PDC brains compared with those in control brains. The RNA expression pattern observed for Kii ALS type brains was similar to that for Kii PDC type brains and unlike those of control and AD brains.\"\n", "!Series_summary\t\"Additionally, pathway and network analyses indicated that the molecular pathogenic mechanism underlying Kii ALS/PDC may be associated with the oxidative phosphorylation of mitochondria, ribosomes, and the synaptic vesicle cycle; in particular, upstream regulators of these mechanisms may be found in synapses and during synaptic trafficking. Therefore, we propose the novel disease concept of “synaptopathy” for Kii ALS/PDC. Furthermore, phenotypic differences between Kii ALS type and Kii PDC type were observed, based on the human leukocyte antigen (HLA) haplotype.\"\n", "!Series_summary\t\"We performed exhaustive transcriptome analyses of Kii ALS/PDC brains, for the first time, and revealed new insights indicating that Kii ALS/PDC may be a synaptopathy. Determining the relationship between synaptic dysfunction and the pathogenesis of ALS/PDC may provide a new step toward understanding this mysterious disease.\"\n", "!Series_overall_design\t\"Total RNA was extracted with an RNeasy Kit (Qiagen, Hilden, Germany), and RNA quality was assessed using an Agilent 2100 bioanalyzer (Agilent Technologies, Palo Alto, CA, USA). Total RNA (100 ng) was reverse transcribed, labeled with biotin, using a TargetAmp-Nano Labeling kit (Epicentre, Madison, WI, USA), and hybridized to a HumanHT-12 v4 Expression BeadChip (Illumina, San Diego, CA, USA). The arrays were washed and stained, using Cy3-Streptavidin, and then scanned with the BeadChip Scanner iScan System (Illumina, San Diego, CA, USA), according to the manufacturer’s instructions. The raw probe intensity data were normalized [RMA normalization (85th percentile), Low signal cutoff (cut off value: 100), Log transformation (Base 2), Ratio to control samples (mean)] by using the transcriptome data analysis software Subio Platform (Subio, Kagoshima, Japan).\"\n", "Sample Characteristics Dictionary:\n", "{0: ['subject id: CT1', 'subject id: CT2', 'subject id: CT3', 'subject id: AD1', 'subject id: AD2', 'subject id: AD3', 'clinical phenotypes: ALS', 'clinical phenotypes: ALS+D', 'clinical phenotypes: PDC+A', 'clinical phenotypes: PDC'], 1: ['clinical phenotypes: Healthy Control', 'clinical phenotypes: Alzheimer`s Disease', 'gender: Female', 'gender: Male'], 2: ['gender: Male', 'age: 66', 'age: 77', 'age: 70', 'age: 74', 'age: 76', 'age: 60', 'age: 79', 'age: 71', 'age: 63', 'age: 65', 'age: 81', 'age: 73', 'age: 72', 'age: 75', 'age: 85'], 3: ['age: 75', 'age: 76', 'age: 83', 'age: 84', 'age: 87', 'age: 88', 'age: 67', 'age: 68', 'age: 86', 'age: 74', 'tissue: Human Postmortem Brain'], 4: ['tissue: Human Postmortem Brain', 'tissue subtype: Frontal lobe', 'tissue subtype: Temporal lobe'], 5: ['tissue subtype: Frontal lobe', 'tissue subtype: Temporal lobe', nan]}\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": "09719fc4", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "8a7355e0", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:27:50.723450Z", "iopub.status.busy": "2025-03-25T06:27:50.723341Z", "iopub.status.idle": "2025-03-25T06:27:50.735041Z", "shell.execute_reply": "2025-03-25T06:27:50.734652Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Preview of selected clinical features: {'Sample_0': [0.0, nan, nan], 'Sample_1': [0.0, 66.0, nan], 'Sample_2': [0.0, 77.0, 0.0], 'Sample_3': [0.0, 70.0, 1.0], 'Sample_4': [0.0, 74.0, nan], 'Sample_5': [0.0, 76.0, nan], 'Sample_6': [1.0, 60.0, nan], 'Sample_7': [1.0, 79.0, nan], 'Sample_8': [1.0, 71.0, nan], 'Sample_9': [1.0, 63.0, nan], 'Sample_10': [nan, 65.0, nan], 'Sample_11': [nan, 81.0, nan], 'Sample_12': [nan, 73.0, nan], 'Sample_13': [nan, 72.0, nan], 'Sample_14': [nan, 75.0, nan], 'Sample_15': [nan, 85.0, nan]}\n", "Clinical data saved to ../../output/preprocess/Amyotrophic_Lateral_Sclerosis/clinical_data/GSE139384.csv\n" ] } ], "source": [ "import pandas as pd\n", "import numpy as np\n", "import os\n", "import json\n", "from typing import Optional, Callable, Dict, Any\n", "\n", "# 1. Gene Expression Data Availability\n", "# Based on the background information, this dataset appears to contain gene expression data\n", "# The study mentions \"microarray data\" and using HumanHT-12 v4 Expression BeadChip\n", "# This indicates gene expression data, not just miRNA or methylation data\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "# Looking for trait data (ALS) in the sample characteristics\n", "# In key 0, we find 'clinical phenotypes: ALS', 'clinical phenotypes: ALS+D', etc.\n", "# Key 1 contains 'clinical phenotypes: Healthy Control' and 'clinical phenotypes: Alzheimer`s Disease'\n", "# This suggests key 0 contains the phenotype information for the subjects including ALS\n", "trait_row = 0\n", "\n", "# Looking for age data\n", "# In key 2 and 3, we find multiple 'age: XX' entries\n", "# This suggests age data is available\n", "age_row = 2 # Choose key 2 as it has more age entries\n", "\n", "# Looking for gender data\n", "# In key 1, we find 'gender: Female' and 'gender: Male'\n", "# In key 2, we find 'gender: Male'\n", "# This suggests key 1 contains more complete gender information\n", "gender_row = 1\n", "\n", "# 2.2 Data Type Conversion Functions\n", "def convert_trait(value):\n", " \"\"\"Convert trait value to binary (0 for control, 1 for ALS/PDC)\"\"\"\n", " if pd.isna(value):\n", " return None\n", " \n", " # Extract the value after colon\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Classify based on clinical phenotypes\n", " if value.lower() in ['healthy control', 'ct1', 'ct2', 'ct3']:\n", " return 0 # Control\n", " elif any(term in value.lower() for term in ['als', 'pdc', 'amyotrophic lateral sclerosis', 'parkinsonism-dementia complex']):\n", " return 1 # ALS/PDC case\n", " elif value.lower() in ['alzheimer`s disease', 'ad1', 'ad2', 'ad3']:\n", " return 0 # Treat Alzheimer's as non-ALS/PDC for this analysis\n", " else:\n", " return None # Unknown\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age value to continuous numeric\"\"\"\n", " if pd.isna(value):\n", " return None\n", " \n", " # Extract the value after colon\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Try to convert to integer\n", " try:\n", " return int(value)\n", " except ValueError:\n", " return None # Return None if conversion fails\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender value to binary (0 for female, 1 for male)\"\"\"\n", " if pd.isna(value):\n", " return None\n", " \n", " # Extract the value after colon\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Convert to binary\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", "# Determine trait availability\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", "# Check if trait_row is not None\n", "if trait_row is not None:\n", " # Create a proper DataFrame structure for the geo_select_clinical_features function\n", " # In GEO data format, rows are characteristics and columns are samples\n", " # Here we'll create a simple DataFrame where each row corresponds to a sample characteristic key\n", " \n", " # Sample characteristics dictionary\n", " sample_char_dict = {\n", " 0: ['subject id: CT1', 'subject id: CT2', 'subject id: CT3', 'subject id: AD1', 'subject id: AD2', 'subject id: AD3', 'clinical phenotypes: ALS', 'clinical phenotypes: ALS+D', 'clinical phenotypes: PDC+A', 'clinical phenotypes: PDC'], \n", " 1: ['clinical phenotypes: Healthy Control', 'clinical phenotypes: Alzheimer`s Disease', 'gender: Female', 'gender: Male'], \n", " 2: ['gender: Male', 'age: 66', 'age: 77', 'age: 70', 'age: 74', 'age: 76', 'age: 60', 'age: 79', 'age: 71', 'age: 63', 'age: 65', 'age: 81', 'age: 73', 'age: 72', 'age: 75', 'age: 85'], \n", " 3: ['age: 75', 'age: 76', 'age: 83', 'age: 84', 'age: 87', 'age: 88', 'age: 67', 'age: 68', 'age: 86', 'age: 74', 'tissue: Human Postmortem Brain'], \n", " 4: ['tissue: Human Postmortem Brain', 'tissue subtype: Frontal lobe', 'tissue subtype: Temporal lobe'], \n", " 5: ['tissue subtype: Frontal lobe', 'tissue subtype: Temporal lobe', float('nan')]\n", " }\n", " \n", " # For the geo_select_clinical_features function, we need a DataFrame with row indices as row numbers\n", " # and each value as a separate \"sample\"\n", " # Create a DataFrame with a single row for each key in the dictionary\n", " rows = []\n", " for key, values in sample_char_dict.items():\n", " row_data = {f'Sample_{i}': val for i, val in enumerate(values)}\n", " rows.append(row_data)\n", " \n", " # Convert to DataFrame\n", " clinical_data = pd.DataFrame(rows)\n", " \n", " # Extract clinical features\n", " selected_clinical_df = geo_select_clinical_features(\n", " clinical_df=clinical_data,\n", " trait=trait,\n", " trait_row=trait_row,\n", " convert_trait=convert_trait,\n", " age_row=age_row,\n", " convert_age=convert_age,\n", " gender_row=gender_row,\n", " convert_gender=convert_gender\n", " )\n", " \n", " # Preview the extracted features\n", " preview = preview_df(selected_clinical_df)\n", " print(\"Preview of selected clinical features:\", preview)\n", " \n", " # Create the directory if it doesn't exist\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " \n", " # Save to CSV\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": "b829a08c", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "a172ae7c", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:27:50.736205Z", "iopub.status.busy": "2025-03-25T06:27:50.736100Z", "iopub.status.idle": "2025-03-25T06:27:50.761264Z", "shell.execute_reply": "2025-03-25T06:27:50.760876Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "First 20 gene/probe identifiers:\n", "Index(['ILMN_1343291', 'ILMN_1343295', 'ILMN_1651228', 'ILMN_1651229',\n", " 'ILMN_1651254', 'ILMN_1651262', 'ILMN_1651315', 'ILMN_1651354',\n", " 'ILMN_1651385', 'ILMN_1651405', 'ILMN_1651429', 'ILMN_1651438',\n", " 'ILMN_1651498', 'ILMN_1651680', 'ILMN_1651705', 'ILMN_1651719',\n", " 'ILMN_1651735', 'ILMN_1651745', 'ILMN_1651799', 'ILMN_1651819'],\n", " dtype='object', name='ID')\n", "\n", "Gene data dimensions: 7154 genes × 33 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": "1c5de2cb", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "5dd95560", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:27:50.762409Z", "iopub.status.busy": "2025-03-25T06:27:50.762305Z", "iopub.status.idle": "2025-03-25T06:27:50.764221Z", "shell.execute_reply": "2025-03-25T06:27:50.763840Z" } }, "outputs": [], "source": [ "# These identifiers like \"ILMN_1343291\" are Illumina probe IDs, not standard human gene symbols\n", "# They are from Illumina BeadArray microarray platforms and need to be mapped to gene symbols\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "46dda59b", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "a289e318", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:27:50.765369Z", "iopub.status.busy": "2025-03-25T06:27:50.765268Z", "iopub.status.idle": "2025-03-25T06:27:52.096580Z", "shell.execute_reply": "2025-03-25T06:27:52.096112Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "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.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" ] } ], "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": "d120c036", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "4a35f0da", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:27:52.098048Z", "iopub.status.busy": "2025-03-25T06:27:52.097914Z", "iopub.status.idle": "2025-03-25T06:27:52.216542Z", "shell.execute_reply": "2025-03-25T06:27:52.215892Z" } }, "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", "\n", "After mapping: 5550 genes × 33 samples\n", "\n", "First 10 mapped gene symbols:\n", "Index(['A2BP1', 'A2M', 'AADACL1', 'AADAT', 'AAGAB', 'AARS', 'AARSD1',\n", " 'AASDHPPT', 'AATK', 'ABAT'],\n", " dtype='object', name='Gene')\n", "\n", "Gene expression data saved to ../../output/preprocess/Amyotrophic_Lateral_Sclerosis/gene_data/GSE139384.csv\n" ] } ], "source": [ "# 1. Identify which columns in the gene annotation dataframe correspond to probe IDs and gene symbols\n", "# Looking at the gene annotation preview, we can see:\n", "# - 'ID' column contains the ILMN_xxxx identifiers that match our gene expression data\n", "# - 'Symbol' column contains the gene symbols we need to map to\n", "\n", "# 2. Extract gene mapping data using the function from the library\n", "gene_mapping = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Symbol')\n", "\n", "# Print preview of the mapping to verify\n", "print(\"\\nGene mapping preview:\")\n", "print(preview_df(gene_mapping))\n", "\n", "# 3. Apply gene mapping to convert probe-level measurements to gene-level expression\n", "# Use the apply_gene_mapping function which handles the many-to-many relation\n", "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n", "\n", "# Print information about the mapped gene data\n", "print(f\"\\nAfter mapping: {gene_data.shape[0]} genes × {gene_data.shape[1]} samples\")\n", "print(\"\\nFirst 10 mapped gene symbols:\")\n", "print(gene_data.index[:10])\n", "\n", "# Save the gene expression data to a file\n", "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", "gene_data.to_csv(out_gene_data_file)\n", "print(f\"\\nGene expression data saved to {out_gene_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "0020d61d", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "910068ce", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:27:52.218552Z", "iopub.status.busy": "2025-03-25T06:27:52.218390Z", "iopub.status.idle": "2025-03-25T06:27:52.435541Z", "shell.execute_reply": "2025-03-25T06:27:52.434926Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape after normalization: (5434, 33)\n", "First 5 gene symbols after normalization: Index(['A2M', 'AADAT', 'AAGAB', 'AARS1', 'AARSD1'], dtype='object', name='Gene')\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data saved to ../../output/preprocess/Amyotrophic_Lateral_Sclerosis/gene_data/GSE139384.csv\n", "Loaded and restructured clinical data from ../../output/preprocess/Amyotrophic_Lateral_Sclerosis/clinical_data/GSE139384.csv\n", "Clinical data shape: (16, 3)\n", "Clinical data preview: {'Amyotrophic_Lateral_Sclerosis': [0.0, 0.0, 0.0], 'Age': [nan, 66.0, 77.0], 'Gender': [nan, nan, 0.0]}\n", "No common samples found between clinical and gene expression data.\n", "Abnormality detected in the cohort: GSE139384. Preprocessing failed.\n", "Dataset deemed not usable for associational studies.\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. Load the previously saved clinical data\n", "try:\n", " # Load the clinical data that was already processed and saved in step 2\n", " clinical_data_df = pd.read_csv(out_clinical_data_file)\n", " \n", " # Transpose the data so samples are rows and features are columns\n", " clinical_data_df = clinical_data_df.T\n", " \n", " # Set proper column names, assuming first row is trait, second is Age, third is Gender\n", " clinical_data_df.columns = [trait, 'Age', 'Gender']\n", " \n", " # Remove the header row if it became the first row after transposition\n", " if clinical_data_df.index[0] == '0':\n", " clinical_data_df = clinical_data_df.iloc[1:]\n", " \n", " # Convert sample IDs to match gene expression data format\n", " # Remove 'Sample_' prefix if present\n", " clinical_data_df.index = clinical_data_df.index.str.replace('Sample_', 'GSM', regex=False)\n", " \n", " is_trait_available = True\n", " print(f\"Loaded and restructured clinical data from {out_clinical_data_file}\")\n", " print(f\"Clinical data shape: {clinical_data_df.shape}\")\n", " print(f\"Clinical data preview: {preview_df(clinical_data_df, n=3)}\")\n", "except Exception as e:\n", " print(f\"Error loading or processing clinical data: {e}\")\n", " is_trait_available = False\n", "\n", "# 3. Link clinical and genetic data if trait data is available\n", "if is_trait_available:\n", " # Find common samples between clinical and gene data\n", " common_samples = set(clinical_data_df.index).intersection(set(normalized_gene_data.columns))\n", " if len(common_samples) == 0:\n", " print(\"No common samples found between clinical and gene expression data.\")\n", " is_trait_available = False\n", " is_biased = True\n", " linked_data = pd.DataFrame()\n", " else:\n", " # Filter to keep only common samples\n", " clinical_data_filtered = clinical_data_df.loc[list(common_samples)]\n", " gene_data_filtered = normalized_gene_data[list(common_samples)]\n", " \n", " # Combine clinical and gene expression data\n", " linked_data = pd.concat([\n", " clinical_data_filtered,\n", " gene_data_filtered.T\n", " ], axis=1)\n", " \n", " print(f\"Linked data shape before handling missing values: {linked_data.shape}\")\n", " \n", " # 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", " # 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 is unavailable in this dataset.\")\n", " is_biased = True # Dataset can't be used without trait data\n", " linked_data = pd.DataFrame() # Empty DataFrame\n", "\n", "# 5. Validate and save cohort info\n", "note = \"\"\n", "if is_trait_available:\n", " note = \"Dataset contains gene expression data from ALS patients with clinical information.\"\n", "else:\n", " note = \"Dataset contains gene expression data from ALS patients, but lacks trait information (disease status) required for associational studies.\"\n", "\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 if not linked_data.empty else pd.DataFrame(index=normalized_gene_data.columns),\n", " note=note\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 }