{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "a390bba5", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:18:00.909763Z", "iopub.status.busy": "2025-03-25T05:18:00.909589Z", "iopub.status.idle": "2025-03-25T05:18:01.092692Z", "shell.execute_reply": "2025-03-25T05:18:01.092254Z" } }, "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 = \"Gaucher_Disease\"\n", "cohort = \"GSE124283\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Gaucher_Disease\"\n", "in_cohort_dir = \"../../input/GEO/Gaucher_Disease/GSE124283\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Gaucher_Disease/GSE124283.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Gaucher_Disease/gene_data/GSE124283.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Gaucher_Disease/clinical_data/GSE124283.csv\"\n", "json_path = \"../../output/preprocess/Gaucher_Disease/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "eb3f2d4c", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "b34c1409", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:18:01.094400Z", "iopub.status.busy": "2025-03-25T05:18:01.094214Z", "iopub.status.idle": "2025-03-25T05:18:01.325772Z", "shell.execute_reply": "2025-03-25T05:18:01.325236Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Changes in the level of expression of genes involved in the pathogenic mechanisms in rare, inherited metabolic diseases.\"\n", "!Series_summary\t\"Inherited metabolic diseases belong to the group of rare diseases (so called ‘orphan diseases’) whose incidence is less than 1: 5 000 live births. Among these diseases the lysosomal storage diseases (LSD) are also distinguished, which are caused by disorders in the lysosomal system resulting from the mutations in the genes coding for lysosomal hydrolases, cofactors, enzymes involved in the posttranslational processing, and proteins present in the lysosomal membrane. Although about 70 LSD are recognized so far, their pathomechanism is almost unknown. Hitherto existing results of scientific investigations indicate that different cellular pathways and events are involved in the pathogenic processes: autophagy, apoptosis, toxic action of lyso- derivatives of lipid compounds, disordered Ca2+ ions intracellular homeostasis, secondary storage of macromolecular compounds, signal transduction, inflammatory processes, deficient by-products and many more. We are especially interested in the explanation of pathomechanisms of Gaucher disease and Niemann-Pick type C disease (for the latter disease there is no therapy officially accepted). In this project we aim to experimentally explain: - which cellular pathways and mechanisms are activated and inactivated in cells originating from patients with different LSD and healthy individuals - are there differences in genes expression in different diseases - are gene expression changes related to known and observed biochemical and clinical changes.\"\n", "!Series_overall_design\t\"Material for the study consists of RNA samples isolated from cultured skin fibroblasts obtained from 20 individuals, in whom no LSD was diagnosed (healthy persons), 20 patients in whom Niemann-Pick type C disease has been diagnosed, and 5 patients with Gaucher disease. Changes in genes expression were investigated by means of microarray analysis with the use of the Illumina technology, which enables the tracking of changes in the whole human genome. Results of microarray analysis were verified by quantitative RT-PCR technique.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['patient: K12', 'patient: K14', 'patient: SB', 'patient: SK', 'patient: 91/78', 'patient: K19', 'patient: DA', 'patient: SP', 'patient: K6', 'patient: K7', 'patient: WP', 'patient: BZ', 'patient: K4', 'patient: K5', 'patient: BE', 'patient: KM', 'patient: K8', 'patient: K9', 'patient: K13', 'patient: K15', 'patient: ML', 'patient: GP', 'patient: 14/84', 'patient: 69/84', 'patient: ZJ', 'patient: BB', 'patient: K10', 'patient: K11', 'patient: NP', 'patient: SK_1'], 1: ['viability: alive', 'viability: deceased', 'viability: nie alive', 'viability: N/A'], 2: ['condition: Control', 'condition: NPC-D', 'condition: NPC-N', 'condition: NPC-M', 'condition: NPC?', 'condition: NPC(-)variant?', 'condition: NPC-NBP', 'condition: Gaucher t.1', 'condition: Gaucher', 'condition: NPC(-)-variant', 'condition: N/A', 'condition: NPC(-)'], 3: ['gender: M', 'gender: K', 'gender: N/A']}\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": "799cf5a9", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "a7f952e9", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:18:01.327529Z", "iopub.status.busy": "2025-03-25T05:18:01.327401Z", "iopub.status.idle": "2025-03-25T05:18:01.338588Z", "shell.execute_reply": "2025-03-25T05:18:01.338190Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Preview of selected clinical features:\n", "{0: [0.0, 1.0], 1: [nan, 0.0], 2: [nan, nan], 3: [nan, nan], 4: [nan, nan], 5: [nan, nan], 6: [nan, nan], 7: [1.0, nan], 8: [1.0, nan], 9: [nan, nan], 10: [nan, nan], 11: [nan, nan], 12: [nan, nan], 13: [nan, nan], 14: [nan, nan], 15: [nan, nan], 16: [nan, nan], 17: [nan, nan], 18: [nan, nan], 19: [nan, nan], 20: [nan, nan], 21: [nan, nan], 22: [nan, nan], 23: [nan, nan], 24: [nan, nan], 25: [nan, nan], 26: [nan, nan], 27: [nan, nan], 28: [nan, nan], 29: [nan, nan]}\n", "Clinical data saved to ../../output/preprocess/Gaucher_Disease/clinical_data/GSE124283.csv\n" ] } ], "source": [ "import pandas as pd\n", "import numpy as np\n", "import os\n", "import json\n", "from typing import Dict, Any, Optional, Callable\n", "\n", "# Check if this cohort contains gene expression data\n", "# Based on the background information, this dataset uses microarray analysis with Illumina technology,\n", "# which suggests it contains gene expression data\n", "is_gene_available = True\n", "\n", "# Analyze the sample characteristics dictionary\n", "# trait_row: The 'condition' field at index 2 contains information about Gaucher Disease (our trait)\n", "trait_row = 2\n", "\n", "# Check age_row: There's no clear age information in the sample characteristics\n", "age_row = None\n", "\n", "# Check gender_row: There's gender information at index 3\n", "gender_row = 3\n", "\n", "# Define conversion functions\n", "def convert_trait(value):\n", " \"\"\"Convert trait information to binary format (1 for Gaucher Disease, 0 for control).\"\"\"\n", " if value is None or ':' not in value:\n", " return None\n", " \n", " condition = value.split(':', 1)[1].strip()\n", " \n", " # 1 for Gaucher Disease, 0 for control\n", " if 'Gaucher' in condition:\n", " return 1\n", " elif 'Control' in condition:\n", " return 0\n", " else:\n", " # All other conditions (NPC variants) are not relevant for our Gaucher_Disease study\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age to continuous format.\"\"\"\n", " # No age data available\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender to binary format (0 for female, 1 for male).\"\"\"\n", " if value is None or ':' not in value:\n", " return None\n", " \n", " gender = value.split(':', 1)[1].strip()\n", " \n", " # In the data 'M' appears to be Male and 'K' appears to be Female (likely from a non-English language)\n", " if gender == 'M':\n", " return 1\n", " elif gender == 'K':\n", " return 0\n", " else:\n", " return None\n", "\n", "# Check if trait data is available\n", "is_trait_available = trait_row is not None\n", "\n", "# Validate and save initial cohort info\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", "# If trait data is available, extract clinical features\n", "if trait_row is not None:\n", " # Create a DataFrame from the sample characteristics dictionary provided in the previous output\n", " # The dictionary contains lists of values for each characteristic\n", " sample_chars_dict = {0: ['patient: K12', 'patient: K14', 'patient: SB', 'patient: SK', 'patient: 91/78', 'patient: K19', 'patient: DA', 'patient: SP', 'patient: K6', 'patient: K7', 'patient: WP', 'patient: BZ', 'patient: K4', 'patient: K5', 'patient: BE', 'patient: KM', 'patient: K8', 'patient: K9', 'patient: K13', 'patient: K15', 'patient: ML', 'patient: GP', 'patient: 14/84', 'patient: 69/84', 'patient: ZJ', 'patient: BB', 'patient: K10', 'patient: K11', 'patient: NP', 'patient: SK_1'], \n", " 1: ['viability: alive', 'viability: deceased', 'viability: nie alive', 'viability: N/A'], \n", " 2: ['condition: Control', 'condition: NPC-D', 'condition: NPC-N', 'condition: NPC-M', 'condition: NPC?', 'condition: NPC(-)variant?', 'condition: NPC-NBP', 'condition: Gaucher t.1', 'condition: Gaucher', 'condition: NPC(-)-variant', 'condition: N/A', 'condition: NPC(-)'], \n", " 3: ['gender: M', 'gender: K', 'gender: N/A']}\n", " \n", " # Convert the dictionary to a DataFrame\n", " # We need to transpose the data so that each row represents a characteristic\n", " clinical_data = pd.DataFrame.from_dict(sample_chars_dict, orient='index')\n", " \n", " # Extract clinical features using the library function\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 clinical features\n", " preview = preview_df(selected_clinical_df)\n", " print(\"Preview of selected clinical features:\")\n", " print(preview)\n", " \n", " # Create directory if it doesn't exist\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " \n", " # Save to 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": "db0e529a", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "7cb1401c", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:18:01.339937Z", "iopub.status.busy": "2025-03-25T05:18:01.339827Z", "iopub.status.idle": "2025-03-25T05:18:01.767352Z", "shell.execute_reply": "2025-03-25T05:18:01.766865Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Found data marker at line 65\n", "Header line: \"ID_REF\"\t\"GSM3526881\"\t\"GSM3526882\"\t\"GSM3526883\"\t\"GSM3526884\"\t\"GSM3526885\"\t\"GSM3526886\"\t\"GSM3526887\"\t\"GSM3526888\"\t\"GSM3526889\"\t\"GSM3526890\"\t\"GSM3526891\"\t\"GSM3526892\"\t\"GSM3526893\"\t\"GSM3526894\"\t\"GSM3526895\"\t\"GSM3526896\"\t\"GSM3526897\"\t\"GSM3526898\"\t\"GSM3526899\"\t\"GSM3526900\"\t\"GSM3526901\"\t\"GSM3526902\"\t\"GSM3526903\"\t\"GSM3526904\"\t\"GSM3526905\"\t\"GSM3526906\"\t\"GSM3526907\"\t\"GSM3526908\"\t\"GSM3526909\"\t\"GSM3526910\"\t\"GSM3526911\"\t\"GSM3526912\"\t\"GSM3526913\"\t\"GSM3526914\"\t\"GSM3526915\"\t\"GSM3526916\"\t\"GSM3526917\"\t\"GSM3526918\"\t\"GSM3526919\"\t\"GSM3526920\"\t\"GSM3526921\"\t\"GSM3526922\"\t\"GSM3526923\"\t\"GSM3526924\"\t\"GSM3526925\"\t\"GSM3526926\"\t\"GSM3526927\"\t\"GSM3526928\"\t\"GSM3526929\"\t\"GSM3526930\"\t\"GSM3526931\"\t\"GSM3526932\"\t\"GSM3526933\"\t\"GSM3526934\"\t\"GSM3526935\"\t\"GSM3526936\"\t\"GSM3526937\"\t\"GSM3526938\"\t\"GSM3526939\"\t\"GSM3526940\"\t\"GSM3526941\"\t\"GSM3526942\"\t\"GSM3526943\"\t\"GSM3526944\"\t\"GSM3526945\"\t\"GSM3526946\"\t\"GSM3526947\"\t\"GSM3526948\"\t\"GSM3526949\"\t\"GSM3526950\"\t\"GSM3526951\"\t\"GSM3526952\"\t\"GSM3526953\"\t\"GSM3526954\"\t\"GSM3526955\"\t\"GSM3526956\"\t\"GSM3526957\"\t\"GSM3526958\"\t\"GSM3526959\"\t\"GSM3526960\"\t\"GSM3526961\"\t\"GSM3526962\"\t\"GSM3526963\"\t\"GSM3526964\"\t\"GSM3526965\"\t\"GSM3526966\"\t\"GSM3526967\"\t\"GSM3526968\"\t\"GSM3526969\"\t\"GSM3526970\"\t\"GSM3526971\"\t\"GSM3526972\"\t\"GSM3526973\"\t\"GSM3526974\"\t\"GSM3526975\"\t\"GSM3526976\"\t\"GSM3526977\"\t\"GSM3526978\"\t\"GSM3526979\"\t\"GSM3526980\"\t\"GSM3526981\"\t\"GSM3526982\"\t\"GSM3526983\"\t\"GSM3526984\"\t\"GSM3526985\"\t\"GSM3526986\"\t\"GSM3526987\"\t\"GSM3526988\"\t\"GSM3526989\"\t\"GSM3526990\"\t\"GSM3526991\"\t\"GSM3526992\"\t\"GSM3526993\"\t\"GSM3526994\"\t\"GSM3526995\"\t\"GSM3526996\"\t\"GSM3526997\"\t\"GSM3526998\"\t\"GSM3526999\"\t\"GSM3527000\"\t\"GSM3527001\"\t\"GSM3527002\"\t\"GSM3527003\"\t\"GSM3527004\"\t\"GSM3527005\"\t\"GSM3527006\"\t\"GSM3527007\"\t\"GSM3527008\"\t\"GSM3527009\"\t\"GSM3527010\"\t\"GSM3527011\"\t\"GSM3527012\"\t\"GSM3527013\"\t\"GSM3527014\"\t\"GSM3527015\"\t\"GSM3527016\"\t\"GSM3527017\"\t\"GSM3527018\"\t\"GSM3527019\"\t\"GSM3527020\"\t\"GSM3527021\"\t\"GSM3527022\"\t\"GSM3527023\"\t\"GSM3527024\"\n", "First data line: \"7A5\"\t78.38345\t82.21474\t74.71161\t79.81136\t80.47159\t76.9025\t82.45166\t85.34927\t76.15834\t81.82063\t82.27115\t75.94736\t69.43501\t77.42808\t77.64975\t76.88379\t73.69692\t75.68887\t75.15121\t77.20704\t73.80977\t73.45553\t77.32343\t76.18443\t75.01661\t71.89839\t74.91393\t78.53762\t73.97869\t74.94361\t75.12608\t75.85424\t74.66983\t78.20895\t77.42453\t77.17545\t69.11\t72.02385\t69.76622\t70.60533\t73.56934\t75.46889\t73.57949\t0\t66.70621\t72.40375\t74.03769\t76.09866\t72.21388\t78.51591\t81.10289\t73.3829\t72.71041\t81.26747\t73.8699\t75.12167\t78.02822\t81.36017\t76.16231\t75.21363\t78.55745\t72.56064\t75.67678\t75.15523\t77.02561\t74.92976\t76.73466\t76.61965\t78.17833\t78.51954\t73.85943\t77.33058\t76.01968\t68.55599\t78.74109\t74.86964\t74.20095\t76.10277\t74.28956\t75.17037\t74.06658\t80.33363\t75.92981\t77.49305\t71.10995\t83.86892\t76.48603\t76.61221\t79.75369\t79.631\t79.23531\t72.30463\t78.83817\t81.51241\t77.27526\t80.35665\t76.42541\t77.08178\t77.90689\t75.86201\t77.15479\t77.23869\t80.09388\t76.50962\t78.09692\t77.02253\t77.16192\t72.46059\t78.33937\t78.96638\t73.92971\t83.02076\t77.91759\t77.78872\t78.60682\t79.6782\t76.50158\t74.51113\t78.18716\t78.26022\t77.3425\t73.91426\t73.90949\t82.72894\t75.95629\t77.47718\t77.87585\t82.67387\t77.77105\t77.44579\t79.22388\t78.42108\t75.09417\t79.30391\t80.21326\t81.88577\t75.09053\t78.11129\t75.73129\t75.94836\t81.32369\t78.07611\t79.1494\t75.80711\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Index(['7A5', 'A1BG', 'A1CF', 'A26C3', 'A2BP1', 'A2LD1', 'A2M', 'A2ML1',\n", " 'A3GALT2', 'A4GALT', 'A4GNT', 'AAA1', 'AAAS', 'AACS', 'AACSL', 'AADAC',\n", " 'AADACL1', 'AADACL2', 'AADACL3', 'AADACL4'],\n", " dtype='object', name='ID')\n" ] } ], "source": [ "# 1. Get the file paths for the SOFT file and matrix file\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# 2. First, let's examine the structure of the matrix file to understand its format\n", "import gzip\n", "\n", "# Peek at the first few lines of the file to understand its structure\n", "with gzip.open(matrix_file, 'rt') as file:\n", " # Read first 100 lines to find the header structure\n", " for i, line in enumerate(file):\n", " if '!series_matrix_table_begin' in line:\n", " print(f\"Found data marker at line {i}\")\n", " # Read the next line which should be the header\n", " header_line = next(file)\n", " print(f\"Header line: {header_line.strip()}\")\n", " # And the first data line\n", " first_data_line = next(file)\n", " print(f\"First data line: {first_data_line.strip()}\")\n", " break\n", " if i > 100: # Limit search to first 100 lines\n", " print(\"Matrix table marker not found in first 100 lines\")\n", " break\n", "\n", "# 3. Now try to get the genetic data with better error handling\n", "try:\n", " gene_data = get_genetic_data(matrix_file)\n", " print(gene_data.index[:20])\n", "except KeyError as e:\n", " print(f\"KeyError: {e}\")\n", " \n", " # Alternative approach: manually extract the data\n", " print(\"\\nTrying alternative approach to read the gene data:\")\n", " with gzip.open(matrix_file, 'rt') as file:\n", " # Find the start of the data\n", " for line in file:\n", " if '!series_matrix_table_begin' in line:\n", " break\n", " \n", " # Read the headers and data\n", " import pandas as pd\n", " df = pd.read_csv(file, sep='\\t', index_col=0)\n", " print(f\"Column names: {df.columns[:5]}\")\n", " print(f\"First 20 row IDs: {df.index[:20]}\")\n", " gene_data = df\n" ] }, { "cell_type": "markdown", "id": "2f9ff7a4", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "1cca4d15", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:18:01.768590Z", "iopub.status.busy": "2025-03-25T05:18:01.768467Z", "iopub.status.idle": "2025-03-25T05:18:01.770570Z", "shell.execute_reply": "2025-03-25T05:18:01.770230Z" } }, "outputs": [], "source": [ "# Let's review the gene identifiers in the expression data\n", "# Looking at the first few identifiers:\n", "# '7A5', 'A1BG', 'A1CF', 'A26C3', 'A2BP1', 'A2LD1', 'A2M', 'A2ML1', etc.\n", "\n", "# These appear to be standard human gene symbols. For example:\n", "# - A1BG: Alpha-1-B Glycoprotein\n", "# - A2M: Alpha-2-Macroglobulin\n", "# - AAAS: Achalasia, Adrenocortical Insufficiency, Alacrimia Syndrome\n", "\n", "# Since these are already in the standard HGNC gene symbol format, \n", "# no mapping is required.\n", "\n", "requires_gene_mapping = False\n" ] }, { "cell_type": "markdown", "id": "d316539b", "metadata": {}, "source": [ "### Step 5: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 6, "id": "92d5435b", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:18:01.771688Z", "iopub.status.busy": "2025-03-25T05:18:01.771579Z", "iopub.status.idle": "2025-03-25T05:18:04.083796Z", "shell.execute_reply": "2025-03-25T05:18:04.083371Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Original gene data shape: (31424, 144)\n", "Gene data shape after normalization: (20747, 144)\n", "Sample gene symbols after normalization: ['A1BG', 'A1BG-AS1', 'A1CF', 'A2M', 'A2ML1', 'A3GALT2', 'A4GALT', 'A4GNT', 'AAA1', 'AAAS']\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data saved to ../../output/preprocess/Gaucher_Disease/gene_data/GSE124283.csv\n", "Loaded clinical data shape: (2, 30)\n", "Clinical data columns: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29']\n", "Clinical data head: 0 1 2 3 4 5 6 7 8 9 ... 20 21 22 23 24 25 \\\n", "0 0.0 NaN NaN NaN NaN NaN NaN 1.0 1.0 NaN ... NaN NaN NaN NaN NaN NaN \n", "1 1.0 0.0 NaN NaN NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN \n", "\n", " 26 27 28 29 \n", "0 NaN NaN NaN NaN \n", "1 NaN NaN NaN NaN \n", "\n", "[2 rows x 30 columns]\n", "Clinical data after renaming columns: ['Gaucher_Disease', 'Gender', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29']\n", "Linked data shape: (174, 20749)\n", "Linked data columns: [0, 1, 'A1BG', 'A1BG-AS1', 'A1CF', 'A2M', 'A2ML1', 'A3GALT2', 'A4GALT', 'A4GNT']\n", "Linked data preview (first 5 rows, first 5 columns):\n", " 0 1 A1BG A1BG-AS1 A1CF\n", "Gaucher_Disease 0.0 1.0 NaN NaN NaN\n", "Gender NaN 0.0 NaN NaN NaN\n", "2 NaN NaN NaN NaN NaN\n", "3 NaN NaN NaN NaN NaN\n", "4 NaN NaN NaN NaN NaN\n", "WARNING: 'Gaucher_Disease' column not found in linked data\n", "Column 0 has 2 unique values and might be the trait column\n", "\n", "Missing values before handling:\n", " Trait (Gaucher_Disease) missing: 171 out of 174\n", " Genes with >20% missing: 1\n", " Samples with >5% missing genes: 30\n", "Data shape after handling missing values: (0, 1)\n", "No data remains after handling missing values.\n", "Abnormality detected in the cohort: GSE124283. Preprocessing failed.\n", "A new JSON file was created at: ../../output/preprocess/Gaucher_Disease/cohort_info.json\n", "Data was determined to be unusable or empty and was not saved\n" ] } ], "source": [ "# 1. Extract the gene expression data and normalize gene symbols\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "gene_data = get_genetic_data(matrix_file)\n", "print(f\"Original gene data shape: {gene_data.shape}\")\n", "\n", "# Normalize gene symbols using NCBI Gene database\n", "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"Gene data shape after normalization: {normalized_gene_data.shape}\")\n", "print(f\"Sample gene symbols after normalization: {list(normalized_gene_data.index[:10])}\")\n", "\n", "# Save the normalized gene data\n", "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", "normalized_gene_data.to_csv(out_gene_data_file)\n", "print(f\"Normalized gene data saved to {out_gene_data_file}\")\n", "\n", "# 2. Load the clinical data created in step 2\n", "clinical_df = pd.read_csv(out_clinical_data_file)\n", "print(f\"Loaded clinical data shape: {clinical_df.shape}\")\n", "\n", "# Check clinical data structure and rename columns if needed\n", "print(\"Clinical data columns:\", clinical_df.columns.tolist())\n", "print(\"Clinical data head:\", clinical_df.head())\n", "\n", "# Ensure clinical data has appropriate column names\n", "if trait not in clinical_df.columns and len(clinical_df.columns) >= 1:\n", " # Assuming the first column is the trait column based on the convert_trait function\n", " clinical_df = clinical_df.rename(columns={clinical_df.columns[0]: trait})\n", " if len(clinical_df.columns) >= 2:\n", " # Assuming the second column might be Gender based on the convert_gender function\n", " clinical_df = clinical_df.rename(columns={clinical_df.columns[1]: 'Gender'})\n", "\n", "print(\"Clinical data after renaming columns:\", clinical_df.columns.tolist())\n", "\n", "# Link clinical and genetic data\n", "linked_data = geo_link_clinical_genetic_data(clinical_df, normalized_gene_data)\n", "print(f\"Linked data shape: {linked_data.shape}\")\n", "print(\"Linked data columns:\", linked_data.columns[:10].tolist())\n", "print(\"Linked data preview (first 5 rows, first 5 columns):\")\n", "if linked_data.shape[1] >= 5:\n", " print(linked_data.iloc[:5, :5])\n", "else:\n", " print(linked_data.head())\n", "\n", "# Verify the trait column exists in linked data\n", "if trait not in linked_data.columns:\n", " print(f\"WARNING: '{trait}' column not found in linked data\")\n", " # Try to identify which column might contain the trait data\n", " for col in linked_data.columns:\n", " if linked_data[col].nunique() <= 2 and col not in ['Gender', 'Age']:\n", " print(f\"Column {col} has {linked_data[col].nunique()} unique values and might be the trait column\")\n", " linked_data = linked_data.rename(columns={col: trait})\n", " break\n", "\n", "# 3. Handle missing values\n", "print(\"\\nMissing values before handling:\")\n", "print(f\" Trait ({trait}) missing: {linked_data[trait].isna().sum()} out of {len(linked_data)}\")\n", "if 'Age' in linked_data.columns:\n", " print(f\" Age missing: {linked_data['Age'].isna().sum()} out of {len(linked_data)}\")\n", "if 'Gender' in linked_data.columns:\n", " print(f\" Gender missing: {linked_data['Gender'].isna().sum()} out of {len(linked_data)}\")\n", "\n", "gene_cols = [col for col in linked_data.columns if col not in [trait, 'Age', 'Gender']]\n", "if gene_cols:\n", " print(f\" Genes with >20% missing: {sum(linked_data[gene_cols].isna().mean() > 0.2)}\")\n", " print(f\" Samples with >5% missing genes: {sum(linked_data[gene_cols].isna().mean(axis=1) > 0.05)}\")\n", "\n", "cleaned_data = handle_missing_values(linked_data, trait)\n", "print(f\"Data shape after handling missing values: {cleaned_data.shape}\")\n", "\n", "# 4. Evaluate bias in trait and demographic features\n", "is_trait_biased = False\n", "if len(cleaned_data) > 0:\n", " trait_biased, cleaned_data = judge_and_remove_biased_features(cleaned_data, trait)\n", " is_trait_biased = trait_biased\n", "else:\n", " print(\"No data remains after handling missing values.\")\n", " is_trait_biased = True\n", "\n", "# 5. Final validation and save\n", "is_usable = validate_and_save_cohort_info(\n", " is_final=True, \n", " cohort=cohort, \n", " info_path=json_path, \n", " is_gene_available=len(normalized_gene_data) > 0, \n", " is_trait_available=True, \n", " is_biased=is_trait_biased, \n", " df=cleaned_data,\n", " note=f\"Dataset contains gene expression data for {trait} analysis.\"\n", ")\n", "\n", "# 6. Save if usable\n", "if is_usable and len(cleaned_data) > 0:\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " cleaned_data.to_csv(out_data_file)\n", " print(f\"Linked data saved to {out_data_file}\")\n", "else:\n", " print(\"Data was determined to be unusable or empty and was not saved\")" ] } ], "metadata": { "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.16" } }, "nbformat": 4, "nbformat_minor": 5 }