{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "f52e1d98", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:07:06.078709Z", "iopub.status.busy": "2025-03-25T06:07:06.078609Z", "iopub.status.idle": "2025-03-25T06:07:06.238911Z", "shell.execute_reply": "2025-03-25T06:07:06.238552Z" } }, "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 = \"Parkinsons_Disease\"\n", "cohort = \"GSE101534\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Parkinsons_Disease\"\n", "in_cohort_dir = \"../../input/GEO/Parkinsons_Disease/GSE101534\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Parkinsons_Disease/GSE101534.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Parkinsons_Disease/gene_data/GSE101534.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Parkinsons_Disease/clinical_data/GSE101534.csv\"\n", "json_path = \"../../output/preprocess/Parkinsons_Disease/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "77f5b50d", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "1b0dd491", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:07:06.240337Z", "iopub.status.busy": "2025-03-25T06:07:06.240192Z", "iopub.status.idle": "2025-03-25T06:07:06.396198Z", "shell.execute_reply": "2025-03-25T06:07:06.395834Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Genome-wide expression profiling of the LRRK2-G2019S mutation in hNES cells\"\n", "!Series_summary\t\"Parkinson’s disease (PD) has a neuro-developmental component with multiple genetic predispositions. The most prevalent mutation, LRRK2-G2019S is linked to familial and sporadic PD. Based on the multiple origins of PD and the incomplete penetrance of LRRK2-G2019S, we hypothesize that modifiers in the patient genetic background act as susceptibility factors for developing PD. To assess the developmental component of LRRK2-G2019S pathogenesis, we used 19 human iPSC-derived neuroepithelial stem cell lines (NESCs). Isogenic controls distinguish between LRRK2-G2019S dependent and independent cellular phenotypes. LRRK2-G2019S patient and healthy mutagenized lines showed altered NESC self-renewal. Within patients, phenotypes were only partly LRRK2-G2019S dependent, suggesting Parkinson’s disease (PD) has a neuro-developmental component with multiple genetic predispositions. The most prevalent mutation, LRRK2-G2019S is linked to familial and sporadic PD. Based on the multiple origins of PD and the incomplete penetrance of LRRK2-G2019S, we hypothesize that modifiers in the patient genetic background act as susceptibility factors for developing PD. To assess the developmental component of LRRK2-G2019S pathogenesis, we used 19 human iPSC-derived neuroepithelial stem cell lines (NESCs).\"\n", "!Series_summary\t\"Isogenic controls distinguish between LRRK2-G2019S dependent and independent cellular phenotypes. LRRK2-G2019S patient and healthy mutagenized lines showed altered NESC self-renewal. Within patients, phenotypes were only partly LRRK2-G2019S dependent, suggesting a significant contribution of the genetic background. We identified Serine racemase (SRR) as a novel patient-specific, developmental, genetic modifier contributing to the abberant phenotypes. Its enzymatic product, D-Serine, rescued altered NESC renewal. Susceptibility factors in the genetic background, such as SRR, could be new targets for early PD diagnosis and treatment.\"\n", "!Series_overall_design\t\"51 samples analyzed, 4 outliers excluded based on QC, 17 coditions, 3 biological replicates, 6 LRRK2G2019S patients, 6 healthy indiviuals, 3 gene corrected lines, 2 inserted mutated lines\"\n", "Sample Characteristics Dictionary:\n", "{0: ['mutation: healthy', 'mutation: patient', 'mutation: gene corrected', 'mutation: inserted G2019S']}\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": "db4213b4", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "b9ce7f80", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:07:06.397708Z", "iopub.status.busy": "2025-03-25T06:07:06.397587Z", "iopub.status.idle": "2025-03-25T06:07:06.406517Z", "shell.execute_reply": "2025-03-25T06:07:06.406231Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Clinical features preview: {'GSM2705776': [0.0], 'GSM2705777': [1.0], 'GSM2705778': [1.0], 'GSM2705779': [0.0], 'GSM2705780': [0.0], 'GSM2705781': [0.0], 'GSM2705782': [1.0], 'GSM2705783': [1.0], 'GSM2705784': [1.0], 'GSM2705785': [0.0], 'GSM2705786': [0.0], 'GSM2705787': [0.0], 'GSM2705788': [0.0], 'GSM2705789': [1.0], 'GSM2705790': [1.0], 'GSM2705791': [1.0], 'GSM2705792': [0.0], 'GSM2705793': [0.0], 'GSM2705794': [0.0], 'GSM2705795': [0.0], 'GSM2705796': [0.0], 'GSM2705797': [0.0], 'GSM2705798': [0.0], 'GSM2705799': [0.0], 'GSM2705800': [0.0], 'GSM2705801': [0.0], 'GSM2705802': [1.0], 'GSM2705803': [1.0], 'GSM2705804': [1.0], 'GSM2705805': [1.0], 'GSM2705806': [1.0], 'GSM2705807': [0.0], 'GSM2705808': [0.0], 'GSM2705809': [0.0], 'GSM2705810': [1.0], 'GSM2705811': [1.0], 'GSM2705812': [0.0], 'GSM2705813': [0.0], 'GSM2705814': [1.0], 'GSM2705815': [0.0], 'GSM2705816': [1.0], 'GSM2705817': [1.0], 'GSM2705818': [1.0], 'GSM2705819': [0.0], 'GSM2705820': [0.0], 'GSM2705821': [0.0], 'GSM2705822': [1.0], 'GSM2705823': [1.0], 'GSM2705824': [1.0], 'GSM2705825': [1.0], 'GSM2705826': [1.0]}\n", "Clinical features saved to ../../output/preprocess/Parkinsons_Disease/clinical_data/GSE101534.csv\n" ] } ], "source": [ "import os\n", "import pandas as pd\n", "import json\n", "from typing import Dict, Any, Optional, Callable\n", "\n", "# Review the sample characteristics dictionary\n", "# This dataset is about LRRK2-G2019S mutation in Parkinson's Disease\n", "\n", "# 1. Gene Expression Data Availability\n", "# Based on the background information, this dataset contains genome-wide expression profiling data\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "\n", "# 2.1 Data Availability\n", "# From the sample characteristics dictionary, we see key 0 contains mutation status\n", "# The values include 'healthy', 'patient', 'gene corrected', and 'inserted G2019S'\n", "# The 'patient' vs 'healthy' can be used as our trait value (PD status)\n", "trait_row = 0 # Key in the sample characteristics dictionary\n", "\n", "# There is no age data available\n", "age_row = None\n", "\n", "# There is no gender data available\n", "gender_row = None\n", "\n", "# 2.2 Data Type Conversion\n", "def convert_trait(value: str) -> int:\n", " \"\"\"\n", " Convert trait value (PD mutation status) to binary.\n", " 0: Healthy/gene corrected (no PD)\n", " 1: Patient/inserted G2019S (PD or PD mutation)\n", " \"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract the value after colon if it exists\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " # Convert to binary\n", " if value.lower() == \"healthy\" or value.lower() == \"gene corrected\":\n", " return 0\n", " elif value.lower() == \"patient\" or value.lower() == \"inserted g2019s\":\n", " return 1\n", " else:\n", " return None\n", "\n", "# Age conversion function - not used but defined for completeness\n", "def convert_age(value: str) -> Optional[float]:\n", " return None\n", "\n", "# Gender conversion function - not used but defined for completeness\n", "def convert_gender(value: str) -> Optional[int]:\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Initial filtering on the usability of the dataset\n", "is_trait_available = trait_row is not None\n", "\n", "validate_and_save_cohort_info(\n", " is_final=False,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=is_gene_available,\n", " is_trait_available=is_trait_available\n", ")\n", "\n", "# 4. Clinical Feature Extraction\n", "# Since trait_row is not None, we proceed with clinical feature extraction\n", "if trait_row is not None:\n", " # Ensure the directory exists\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " \n", " # Use the function from the library to extract clinical features\n", " # Assuming clinical_data is already loaded from a previous step\n", " try:\n", " # Check if clinical_data is already defined\n", " clinical_data\n", " except NameError:\n", " # If not defined, we need to create a dataframe based on the sample characteristics\n", " # As a placeholder, using the provided information\n", " clinical_data = pd.DataFrame({0: ['mutation: healthy', 'mutation: patient', 'mutation: gene corrected', 'mutation: inserted G2019S']})\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", " 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(clinical_features)\n", " print(\"Clinical features preview:\", preview)\n", " \n", " # Save the clinical features to a CSV file\n", " clinical_features.to_csv(out_clinical_data_file, index=False)\n", " print(f\"Clinical features saved to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "70715be3", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "0830ad25", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:07:06.407845Z", "iopub.status.busy": "2025-03-25T06:07:06.407740Z", "iopub.status.idle": "2025-03-25T06:07:06.641172Z", "shell.execute_reply": "2025-03-25T06:07:06.640775Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "First 20 gene/probe identifiers:\n", "Index(['16650001', '16650003', '16650005', '16650007', '16650009', '16650011',\n", " '16650013', '16650015', '16650017', '16650019', '16650021', '16650023',\n", " '16650025', '16650027', '16650029', '16650031', '16650033', '16650035',\n", " '16650037', '16650041'],\n", " dtype='object', name='ID')\n" ] } ], "source": [ "# 1. First get the file paths again to access the matrix file\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# 2. Use the get_genetic_data function from the library to get the gene_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) for future observation\n", "print(\"First 20 gene/probe identifiers:\")\n", "print(gene_data.index[:20])\n" ] }, { "cell_type": "markdown", "id": "080dbd45", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "e53a0ccf", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:07:06.642562Z", "iopub.status.busy": "2025-03-25T06:07:06.642293Z", "iopub.status.idle": "2025-03-25T06:07:06.644346Z", "shell.execute_reply": "2025-03-25T06:07:06.643993Z" } }, "outputs": [], "source": [ "# Examining the gene identifiers from the previous step\n", "# These appear to be numeric identifiers (likely probe IDs) rather than standard human gene symbols\n", "# Human gene symbols typically have alphabetic characters (like BRCA1, TP53, etc.)\n", "# Therefore, these identifiers need to be mapped to gene symbols\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "ca131b34", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "62d2d35d", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:07:06.645701Z", "iopub.status.busy": "2025-03-25T06:07:06.645593Z", "iopub.status.idle": "2025-03-25T06:07:09.816188Z", "shell.execute_reply": "2025-03-25T06:07:09.815795Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene annotation preview:\n", "{'ID': ['16657436', '16657440', '16657445', '16657447', '16657450'], 'RANGE_STRAND': ['+', '+', '+', '+', '+'], 'RANGE_START': [12190.0, 29554.0, 69091.0, 160446.0, 317811.0], 'RANGE_END': [13639.0, 31109.0, 70008.0, 161525.0, 328581.0], 'total_probes': [25.0, 28.0, 8.0, 13.0, 36.0], 'GB_ACC': ['NR_046018', nan, nan, nan, 'NR_024368'], 'SPOT_ID': ['chr1:12190-13639', 'chr1:29554-31109', 'chr1:69091-70008', 'chr1:160446-161525', 'chr1:317811-328581'], 'RANGE_GB': ['NC_000001.10', 'NC_000001.10', 'NC_000001.10', 'NC_000001.10', 'NC_000001.10']}\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": "9254e14d", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "0d25bd7b", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:07:09.817889Z", "iopub.status.busy": "2025-03-25T06:07:09.817764Z", "iopub.status.idle": "2025-03-25T06:07:10.967725Z", "shell.execute_reply": "2025-03-25T06:07:10.967330Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene annotation columns: ['ID', 'RANGE_STRAND', 'RANGE_START', 'RANGE_END', 'total_probes', 'GB_ACC', 'SPOT_ID', 'RANGE_GB']\n", "Sample gene data index: Index(['16650001', '16650003', '16650005', '16650007', '16650009'], dtype='object', name='ID')\n", "Number of IDs in gene_data: 53617\n", "Number of IDs in gene_annotation: 2788499\n", "\n", "Checking potential gene identifier columns:\n", "Column 'ID': 2788499 non-null values, samples: ['16657436', '16657440', '16657445']\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Column 'RANGE_STRAND': 2786290 non-null values, samples: ['+', '+', '+']\n", "Column 'RANGE_START': 51772 non-null values, samples: [12190.0, 29554.0, 69091.0]\n", "Column 'RANGE_END': 51772 non-null values, samples: [13639.0, 31109.0, 70008.0]\n", "Column 'total_probes': 51772 non-null values, samples: [25.0, 28.0, 8.0]\n", "Column 'GB_ACC': 17623 non-null values, samples: ['NR_046018', 'NR_024368', 'NR_029406']\n", "Column 'SPOT_ID': 53981 non-null values, samples: ['chr1:12190-13639', 'chr1:29554-31109', 'chr1:69091-70008']\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Column 'RANGE_GB': 47833 non-null values, samples: ['NC_000001.10', 'NC_000001.10', 'NC_000001.10']\n", "\n", "Gene mapping preview (using accession numbers directly):\n", "{'ID': ['16657436', '16657450', '16657476', '16657485', '16657514'], 'Gene': ['NR_046018', 'NR_024368', 'NR_029406', 'XR_132471', 'NR_047526']}\n", "Number of probes with gene information: 17623\n", "\n", "Gene expression data after mapping:\n", "Shape: (16346, 51)\n", "Number of genes: 16346\n", "Sample of genes (up to 5): ['NM_000014', 'NM_000015', 'NM_000019', 'NM_000020', 'NM_000021']\n", "Successfully mapped probes to gene accession numbers.\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data saved to ../../output/preprocess/Parkinsons_Disease/gene_data/GSE101534.csv\n" ] } ], "source": [ "# 1. Examining the gene annotation data and gene_data indexes to determine mapping columns\n", "print(\"Gene annotation columns:\", gene_annotation.columns.tolist())\n", "print(\"Sample gene data index:\", gene_data.index[:5])\n", "\n", "# Print some diagnostic information about our data\n", "print(f\"Number of IDs in gene_data: {len(gene_data.index)}\")\n", "print(f\"Number of IDs in gene_annotation: {len(gene_annotation)}\")\n", "\n", "# Check column contents for potential gene identifiers\n", "print(\"\\nChecking potential gene identifier columns:\")\n", "for col in gene_annotation.columns:\n", " non_null_count = gene_annotation[col].count()\n", " sample_values = gene_annotation[col].dropna().head(3).tolist()\n", " print(f\"Column '{col}': {non_null_count} non-null values, samples: {sample_values}\")\n", "\n", "# Create a mapping dataframe using accession numbers directly without trying to extract symbols\n", "# We'll use GB_ACC directly as our gene identifiers since they're RefSeq/GenBank accessions\n", "mapping_data = gene_annotation[['ID', 'GB_ACC']].dropna()\n", "mapping_data = mapping_data.rename(columns={'GB_ACC': 'Gene'})\n", "mapping_data['Gene'] = mapping_data['Gene'].astype(str) # Ensure gene IDs are strings\n", "\n", "# Print sample of mapping data to verify\n", "print(\"\\nGene mapping preview (using accession numbers directly):\")\n", "print(preview_df(mapping_data))\n", "print(f\"Number of probes with gene information: {len(mapping_data)}\")\n", "\n", "# 3. Apply the mapping to convert probe-level measurements to gene expression data\n", "# Modify the function call to bypass the extract_human_gene_symbols step\n", "# We'll create a custom function that wraps apply_gene_mapping but skips symbol extraction\n", "def apply_direct_gene_mapping(expression_df, mapping_df):\n", " \"\"\"Apply gene mapping without attempting to extract gene symbols.\"\"\"\n", " mapping_df = mapping_df[mapping_df['ID'].isin(expression_df.index)].copy()\n", " mapping_df['num_genes'] = 1 # Each accession is treated as one gene\n", " mapping_df.set_index('ID', inplace=True)\n", " \n", " # Merge and distribute expression values\n", " merged_df = mapping_df.join(expression_df)\n", " expr_cols = [col for col in merged_df.columns if col not in ['Gene', 'num_genes']]\n", " \n", " # Group by accession number and sum the expression values\n", " gene_expression_df = merged_df.groupby('Gene')[expr_cols].sum()\n", " \n", " return gene_expression_df\n", "\n", "# Apply our direct mapping function\n", "mapped_gene_data = apply_direct_gene_mapping(gene_data, mapping_data)\n", "\n", "# Verify the results\n", "print(\"\\nGene expression data after mapping:\")\n", "print(f\"Shape: {mapped_gene_data.shape}\")\n", "print(f\"Number of genes: {len(mapped_gene_data.index)}\")\n", "print(\"Sample of genes (up to 5):\", list(mapped_gene_data.index)[:5] if len(mapped_gene_data.index) > 0 else \"None\")\n", "\n", "# Use the mapping result if successful, otherwise use probe IDs\n", "if len(mapped_gene_data.index) > 0:\n", " gene_data = mapped_gene_data\n", " print(\"Successfully mapped probes to gene accession numbers.\")\n", "else:\n", " print(\"WARNING: Gene mapping failed. Using probe IDs directly as fallback.\")\n", " # gene_data is already in the right format with probe IDs\n", "\n", "# Save the processed gene data to the output file\n", "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", "gene_data.to_csv(out_gene_data_file)\n", "print(f\"Gene expression data saved to {out_gene_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "19a4b529", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "ef5a91c7", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:07:10.969595Z", "iopub.status.busy": "2025-03-25T06:07:10.969451Z", "iopub.status.idle": "2025-03-25T06:07:18.102042Z", "shell.execute_reply": "2025-03-25T06:07:18.100924Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Original gene expression data shape: (16346, 51)\n", "First 5 gene identifiers:\n", "Index(['NM_000014', 'NM_000015', 'NM_000019', 'NM_000020', 'NM_000021'], dtype='object', name='Gene')\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene data saved to ../../output/preprocess/Parkinsons_Disease/gene_data/GSE101534.csv\n", "Loaded clinical data from file\n", "Transposed clinical data to have samples as rows\n", "Clinical data shape: (51, 1)\n", "Clinical data preview:\n", "{'Parkinsons_Disease': [0.0, 1.0, 1.0, 0.0, 0.0]}\n", "Transposed gene data shape: (51, 16346)\n", "Linked data shape: (51, 16347)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Data shape after handling missing values: (51, 16347)\n", "For the feature 'Parkinsons_Disease', the least common label is '1.0' with 24 occurrences. This represents 47.06% of the dataset.\n", "The distribution of the feature 'Parkinsons_Disease' in this dataset is fine.\n", "\n", "Data shape after removing biased features: (51, 16347)\n", "Is the trait biased: False\n", "A new JSON file was created at: ../../output/preprocess/Parkinsons_Disease/cohort_info.json\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data saved to ../../output/preprocess/Parkinsons_Disease/GSE101534.csv\n" ] } ], "source": [ "# 1. Normalize gene symbols from the already mapped gene expression data from Step 6\n", "# Since the gene data contains RefSeq accessions (NM_, NR_) rather than standard gene symbols,\n", "# we'll use these directly without normalization\n", "\n", "# Let's use the original gene_data from Step 6 instead of trying to normalize\n", "print(f\"Original gene expression data shape: {gene_data.shape}\")\n", "print(\"First 5 gene identifiers:\")\n", "print(gene_data.index[:5])\n", "\n", "# Save the gene data without normalization\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 data saved to {out_gene_data_file}\")\n", "\n", "# 2. Load the clinical data that was already processed in Step 2\n", "if os.path.exists(out_clinical_data_file):\n", " clinical_data_processed = pd.read_csv(out_clinical_data_file)\n", " print(\"Loaded clinical data from file\")\n", "else:\n", " # If for some reason the file wasn't saved, recreate the clinical features using the same parameters\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", " # Use the same conversion function and trait_row from Step 2\n", " def convert_trait(value):\n", " if value is None:\n", " return None\n", " \n", " # Extract the value after colon if it exists\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " # Convert to binary\n", " if value.lower() == \"healthy\" or value.lower() == \"gene corrected\":\n", " return 0\n", " elif value.lower() == \"patient\" or value.lower() == \"inserted g2019s\":\n", " return 1\n", " else:\n", " return None\n", " \n", " # Use the exact same parameters as determined in Step 2\n", " clinical_data_processed = geo_select_clinical_features(\n", " clinical_df=clinical_data,\n", " trait=trait,\n", " trait_row=0, # From Step 2\n", " convert_trait=convert_trait,\n", " age_row=None, # From Step 2\n", " convert_age=None,\n", " gender_row=None, # From Step 2\n", " convert_gender=None\n", " )\n", " \n", " # Save it again just to be sure\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " clinical_data_processed.to_csv(out_clinical_data_file, index=True)\n", "\n", "# Ensure clinical data has the right format\n", "# The expected format should have samples as rows and features as columns\n", "# Adjust if needed to match the expected format for the linking step\n", "if clinical_data_processed.shape[0] == 1:\n", " # If it's structured with samples as columns and 1 row for the trait\n", " # Transpose to get samples as rows and features as columns\n", " clinical_data_processed = clinical_data_processed.T\n", " clinical_data_processed.columns = [trait] # Rename column to match the trait\n", " print(\"Transposed clinical data to have samples as rows\")\n", "\n", "print(\"Clinical data shape:\", clinical_data_processed.shape)\n", "print(\"Clinical data preview:\")\n", "print(preview_df(clinical_data_processed))\n", "\n", "# 3. Link clinical and genetic data\n", "# We need to transpose gene_data to match samples as rows\n", "gene_data_t = gene_data.T\n", "print(f\"Transposed gene data shape: {gene_data_t.shape}\")\n", "\n", "# Now combine clinical and genetic data horizontally (samples as rows, features as columns)\n", "if not clinical_data_processed.index.equals(gene_data_t.index):\n", " print(\"WARNING: Sample IDs don't match between clinical and gene data!\")\n", " # Get common samples\n", " common_samples = clinical_data_processed.index.intersection(gene_data_t.index)\n", " print(f\"Found {len(common_samples)} common samples\")\n", " if len(common_samples) > 0:\n", " clinical_data_processed = clinical_data_processed.loc[common_samples]\n", " gene_data_t = gene_data_t.loc[common_samples]\n", "\n", "# Combine data horizontally\n", "linked_data = pd.concat([clinical_data_processed, gene_data_t], axis=1)\n", "print(f\"Linked data shape: {linked_data.shape}\")\n", "\n", "# 4. Handle missing values\n", "# Use handle_missing_values with the correct trait column name\n", "linked_data = handle_missing_values(linked_data, trait)\n", "print(f\"Data shape after handling missing values: {linked_data.shape}\")\n", "\n", "# 5. 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", "print(f\"Is the trait biased: {is_biased}\")\n", "\n", "# 6. 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=True,\n", " is_biased=is_biased,\n", " df=linked_data,\n", " note=\"Dataset contains gene expression data related to LRRK2-G2019S mutation in Parkinson's Disease.\"\n", ")\n", "\n", "# 7. 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. Linked data was not saved.\")" ] } ], "metadata": { "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.16" } }, "nbformat": 4, "nbformat_minor": 5 }