{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "0e53b6c8", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:39:46.907519Z", "iopub.status.busy": "2025-03-25T08:39:46.907284Z", "iopub.status.idle": "2025-03-25T08:39:47.072733Z", "shell.execute_reply": "2025-03-25T08:39:47.072292Z" } }, "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 = \"Duchenne_Muscular_Dystrophy\"\n", "cohort = \"GSE79263\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Duchenne_Muscular_Dystrophy\"\n", "in_cohort_dir = \"../../input/GEO/Duchenne_Muscular_Dystrophy/GSE79263\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Duchenne_Muscular_Dystrophy/GSE79263.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Duchenne_Muscular_Dystrophy/gene_data/GSE79263.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Duchenne_Muscular_Dystrophy/clinical_data/GSE79263.csv\"\n", "json_path = \"../../output/preprocess/Duchenne_Muscular_Dystrophy/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "994963be", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "b762f198", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:39:47.074176Z", "iopub.status.busy": "2025-03-25T08:39:47.074027Z", "iopub.status.idle": "2025-03-25T08:39:47.353416Z", "shell.execute_reply": "2025-03-25T08:39:47.352788Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Analysis of gene expression in hTERT/cdk4 immortalized human myoblasts compared to their primary populations in both undifferentiatied (myoblast) and differentiated (myotube) states\"\n", "!Series_summary\t\"hTERT/cdk4 immortalized myogenic human cell lines represent an important tool for skeletal muscle research, being used as therapeutically-pertinent models of various neuromuscular disorders and in numerous fundamental studies of muscle cell function. However, the cell cycle is linked to other cellular processes such as integrin regulation, the PI3K/Akt pathway, and microtubule stability, raising the question as to whether transgenic modification of the cell cycle results in secondary effects that could undermine the validity of these cell models. Here we subjected healthy and disease lines to intensive transcriptomic analysis, comparing immortalized lines with their parent primary populations in both differentiated and undifferentiated states, and testing their myogenic character by comparison with non-myogenic (CD56-negative) cells. We found that immortalization has no measurable effect on the myogenic cascade or on any other cellular processes, and that it was protective against the systems level effects of senescence that are observed at higher division counts of primary cells.\"\n", "!Series_overall_design\t\"This dataset includes gene expression profiles for 94 samples comprising primary myoblasts and their corresponding immortalized clones in both differentiated and undifferentiated states (average of 4 cell culture replicates each) from 5 human subjects (2 healthy and 3 Duchenne muscular dystropy - DMD), together with primary populations of non-myogenic (CD56-ve) cells from the muscles of 8 other human subjects. Total RNA was extracted from, myoblasts, myotubes (after 9 days of differentiation), or CD56-ve cells by dissolving cell pellets in TRIzol then using PureLink RNA Mini Kit.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['cell type: non-myogenic CD56-negative', 'differentiation state: Myoblast', 'differentiation state: Myotube'], 1: ['differentiation state: NA', 'clonal state: Clone', 'clonal state: Primary'], 2: ['clonal state: NA', 'disease state: healthy', 'disease state: Duchenne muscular dystrophy', 'disease state: Healthy'], 3: ['disease state: NA', nan], 4: ['age: 80y', 'age: 78y', 'age: unknown', 'age: 79y', 'age: 19y', 'age: 17y', 'age: 15y', 'age: 73y', 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": "3e710f57", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "1111ff24", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:39:47.354879Z", "iopub.status.busy": "2025-03-25T08:39:47.354760Z", "iopub.status.idle": "2025-03-25T08:39:47.370452Z", "shell.execute_reply": "2025-03-25T08:39:47.370087Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Clinical Data Preview: {'GSM2090086': [nan, 80.0], 'GSM2090087': [nan, 78.0], 'GSM2090088': [nan, nan], 'GSM2090089': [nan, 79.0], 'GSM2090090': [nan, 19.0], 'GSM2090091': [nan, 17.0], 'GSM2090092': [nan, 15.0], 'GSM2090093': [nan, 73.0], 'GSM2090094': [0.0, nan], 'GSM2090095': [0.0, nan], 'GSM2090096': [0.0, nan], 'GSM2090097': [0.0, nan], 'GSM2090098': [0.0, nan], 'GSM2090099': [0.0, nan], 'GSM2090100': [0.0, nan], 'GSM2090101': [0.0, nan], 'GSM2090102': [0.0, nan], 'GSM2090103': [0.0, nan], 'GSM2090104': [0.0, nan], 'GSM2090105': [0.0, nan], 'GSM2090106': [0.0, nan], 'GSM2090107': [0.0, nan], 'GSM2090108': [0.0, nan], 'GSM2090109': [0.0, nan], 'GSM2090110': [1.0, nan], 'GSM2090111': [1.0, nan], 'GSM2090112': [1.0, nan], 'GSM2090113': [1.0, nan], 'GSM2090114': [1.0, nan], 'GSM2090115': [1.0, nan], 'GSM2090116': [1.0, nan], 'GSM2090117': [1.0, nan], 'GSM2090118': [1.0, nan], 'GSM2090119': [1.0, nan], 'GSM2090120': [1.0, nan], 'GSM2090121': [1.0, nan], 'GSM2090122': [1.0, nan], 'GSM2090123': [1.0, nan], 'GSM2090124': [1.0, nan], 'GSM2090125': [1.0, nan], 'GSM2090126': [1.0, nan], 'GSM2090127': [1.0, nan], 'GSM2090128': [1.0, nan], 'GSM2090129': [1.0, nan], 'GSM2090130': [1.0, nan], 'GSM2090131': [1.0, nan], 'GSM2090132': [0.0, nan], 'GSM2090133': [0.0, nan], 'GSM2090134': [0.0, nan], 'GSM2090135': [0.0, nan], 'GSM2090136': [0.0, nan], 'GSM2090137': [0.0, nan], 'GSM2090138': [0.0, nan], 'GSM2090139': [0.0, nan], 'GSM2090140': [0.0, nan], 'GSM2090141': [0.0, nan], 'GSM2090142': [0.0, nan], 'GSM2090143': [0.0, nan], 'GSM2090144': [0.0, nan], 'GSM2090145': [0.0, nan], 'GSM2090146': [0.0, nan], 'GSM2090147': [0.0, nan], 'GSM2090148': [0.0, nan], 'GSM2090149': [0.0, nan], 'GSM2090150': [0.0, nan], 'GSM2090151': [0.0, nan], 'GSM2090152': [1.0, nan], 'GSM2090153': [1.0, nan], 'GSM2090154': [1.0, nan], 'GSM2090155': [1.0, nan], 'GSM2090156': [1.0, nan], 'GSM2090157': [1.0, nan], 'GSM2090158': [1.0, nan], 'GSM2090159': [1.0, nan], 'GSM2090160': [1.0, nan], 'GSM2090161': [1.0, nan], 'GSM2090162': [1.0, nan], 'GSM2090163': [1.0, nan], 'GSM2090164': [1.0, nan], 'GSM2090165': [1.0, nan], 'GSM2090166': [1.0, nan], 'GSM2090167': [1.0, nan], 'GSM2090168': [1.0, nan], 'GSM2090169': [1.0, nan], 'GSM2090170': [1.0, nan], 'GSM2090171': [1.0, nan], 'GSM2090172': [1.0, nan], 'GSM2090173': [1.0, nan], 'GSM2090174': [1.0, nan], 'GSM2090175': [1.0, nan], 'GSM2090176': [1.0, nan], 'GSM2090177': [1.0, nan], 'GSM2090178': [1.0, nan], 'GSM2090179': [1.0, nan]}\n", "Clinical data saved to ../../output/preprocess/Duchenne_Muscular_Dystrophy/clinical_data/GSE79263.csv\n" ] } ], "source": [ "import pandas as pd\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, the dataset contains gene expression data\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "# For trait (Duchenne Muscular Dystrophy), we can see it in row 2 with 'disease state'\n", "trait_row = 2\n", "\n", "# For age, we can see it in row 4\n", "age_row = 4\n", "\n", "# For gender, there's no information in the sample characteristics\n", "gender_row = None\n", "\n", "# 2.2 Data Type Conversion\n", "def convert_trait(value):\n", " if pd.isna(value):\n", " return None\n", " \n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip().lower()\n", " else:\n", " value = value.lower()\n", " \n", " if \"duchenne\" in value or \"dmd\" in value:\n", " return 1\n", " elif \"healthy\" in value:\n", " return 0\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " if pd.isna(value):\n", " return None\n", " \n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip().lower()\n", " \n", " if \"unknown\" in value:\n", " return None\n", " \n", " # Extract numeric values\n", " import re\n", " age_match = re.search(r'(\\d+)', value)\n", " if age_match:\n", " return int(age_match.group(1))\n", " else:\n", " return None\n", "\n", "# 3. Save Metadata - Initial Filtering\n", "# Determine if trait data is available\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", "if trait_row is not None:\n", " try:\n", " # Try to find and load the clinical data\n", " # Check if the sample characteristics data is already available from a previous step\n", " # This assumes that clinical_data was created in a previous step\n", " # and represents the sample characteristics dictionary shown in the output\n", " if 'clinical_data' in locals() or 'clinical_data' in globals():\n", " # Use existing clinical_data variable\n", " pass\n", " else:\n", " # Try different possible file paths/formats for clinical data\n", " potential_paths = [\n", " os.path.join(in_cohort_dir, \"clinical_data.csv\"),\n", " os.path.join(in_cohort_dir, \"sample_characteristics.csv\"),\n", " os.path.join(in_cohort_dir, \"characteristics.csv\")\n", " ]\n", " \n", " clinical_data = None\n", " for path in potential_paths:\n", " if os.path.exists(path):\n", " clinical_data = pd.read_csv(path)\n", " print(f\"Loaded clinical data from {path}\")\n", " break\n", " \n", " if clinical_data is None:\n", " # If no file is found, create a DataFrame from the sample characteristics dictionary\n", " # This is a placeholder based on the structure shown in the previous output\n", " sample_chars = {\n", " 0: ['cell type: non-myogenic CD56-negative', 'differentiation state: Myoblast', 'differentiation state: Myotube'], \n", " 1: ['differentiation state: NA', 'clonal state: Clone', 'clonal state: Primary'], \n", " 2: ['clonal state: NA', 'disease state: healthy', 'disease state: Duchenne muscular dystrophy', 'disease state: Healthy'], \n", " 3: ['disease state: NA', None], \n", " 4: ['age: 80y', 'age: 78y', 'age: unknown', 'age: 79y', 'age: 19y', 'age: 17y', 'age: 15y', 'age: 73y', None]\n", " }\n", " \n", " # Convert the dictionary to a DataFrame\n", " # This is an approximation - in reality we'd need to know how samples map to these characteristics\n", " clinical_data = pd.DataFrame(sample_chars)\n", " print(\"Created clinical data DataFrame from sample characteristics dictionary\")\n", " \n", " if clinical_data is not None:\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=None\n", " )\n", " \n", " # Preview the data\n", " preview = preview_df(selected_clinical_df)\n", " print(\"Clinical Data Preview:\", 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 the clinical data\n", " selected_clinical_df.to_csv(out_clinical_data_file, index=False)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n", " else:\n", " print(\"Warning: No clinical data could be loaded or created\")\n", " \n", " except Exception as e:\n", " print(f\"Error in clinical data extraction: {e}\")\n", " print(\"Continuing with other preprocessing steps...\")\n" ] }, { "cell_type": "markdown", "id": "4f3a8ed5", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "1e937509", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:39:47.371469Z", "iopub.status.busy": "2025-03-25T08:39:47.371359Z", "iopub.status.idle": "2025-03-25T08:39:47.867582Z", "shell.execute_reply": "2025-03-25T08:39:47.866957Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Found data marker at line 62\n", "Header line: \"ID_REF\"\t\"GSM2090086\"\t\"GSM2090087\"\t\"GSM2090088\"\t\"GSM2090089\"\t\"GSM2090090\"\t\"GSM2090091\"\t\"GSM2090092\"\t\"GSM2090093\"\t\"GSM2090094\"\t\"GSM2090095\"\t\"GSM2090096\"\t\"GSM2090097\"\t\"GSM2090098\"\t\"GSM2090099\"\t\"GSM2090100\"\t\"GSM2090101\"\t\"GSM2090102\"\t\"GSM2090103\"\t\"GSM2090104\"\t\"GSM2090105\"\t\"GSM2090106\"\t\"GSM2090107\"\t\"GSM2090108\"\t\"GSM2090109\"\t\"GSM2090110\"\t\"GSM2090111\"\t\"GSM2090112\"\t\"GSM2090113\"\t\"GSM2090114\"\t\"GSM2090115\"\t\"GSM2090116\"\t\"GSM2090117\"\t\"GSM2090118\"\t\"GSM2090119\"\t\"GSM2090120\"\t\"GSM2090121\"\t\"GSM2090122\"\t\"GSM2090123\"\t\"GSM2090124\"\t\"GSM2090125\"\t\"GSM2090126\"\t\"GSM2090127\"\t\"GSM2090128\"\t\"GSM2090129\"\t\"GSM2090130\"\t\"GSM2090131\"\t\"GSM2090132\"\t\"GSM2090133\"\t\"GSM2090134\"\t\"GSM2090135\"\t\"GSM2090136\"\t\"GSM2090137\"\t\"GSM2090138\"\t\"GSM2090139\"\t\"GSM2090140\"\t\"GSM2090141\"\t\"GSM2090142\"\t\"GSM2090143\"\t\"GSM2090144\"\t\"GSM2090145\"\t\"GSM2090146\"\t\"GSM2090147\"\t\"GSM2090148\"\t\"GSM2090149\"\t\"GSM2090150\"\t\"GSM2090151\"\t\"GSM2090152\"\t\"GSM2090153\"\t\"GSM2090154\"\t\"GSM2090155\"\t\"GSM2090156\"\t\"GSM2090157\"\t\"GSM2090158\"\t\"GSM2090159\"\t\"GSM2090160\"\t\"GSM2090161\"\t\"GSM2090162\"\t\"GSM2090163\"\t\"GSM2090164\"\t\"GSM2090165\"\t\"GSM2090166\"\t\"GSM2090167\"\t\"GSM2090168\"\t\"GSM2090169\"\t\"GSM2090170\"\t\"GSM2090171\"\t\"GSM2090172\"\t\"GSM2090173\"\t\"GSM2090174\"\t\"GSM2090175\"\t\"GSM2090176\"\t\"GSM2090177\"\t\"GSM2090178\"\t\"GSM2090179\"\n", "First data line: \"ILMN_1343291\"\t6781.356181\t7322.433553\t7629.757351\t7629.757351\t7161.7875\t7322.433553\t6781.356181\t6781.356181\t6674.727202\t7629.757351\t6093.0695\t6501.572617\t6781.356181\t6995.556776\t6580.845478\t6995.556776\t7322.433553\t6880.699574\t7629.757351\t7161.7875\t6363.804712\t7629.757351\t7322.433553\t7161.7875\t7161.7875\t7629.757351\t6245.360712\t6580.845478\t6781.356181\t6674.727202\t6674.727202\t7322.433553\t6580.845478\t7161.7875\t6995.556776\t7161.7875\t6880.699574\t7322.433553\t6580.845478\t7161.7875\t7322.433553\t7322.433553\t6781.356181\t6297.229223\t7629.757351\t6995.556776\t5066.114149\t5084.816532\t5304.644\t4832.331191\t5842.57817\t5400.466478\t6245.360712\t5476.208276\t6008.865489\t5737.821351\t5197.462766\t6093.0695\t7322.433553\t6781.356181\t5775.262308\t5373.947989\t5178.011659\t6501.572617\t5680.925755\t5680.925755\t5028.094861\t5648.459202\t6194.08934\t5737.821351\t6093.0695\t5239.944925\t7322.433553\t7161.7875\t7161.7875\t6995.556776\t7629.757351\t7161.7875\t7629.757351\t7322.433553\t7629.757351\t7161.7875\t6674.727202\t7322.433553\t6501.572617\t7161.7875\t6048.842617\t6008.865489\t5556.937712\t6008.865489\t4735.286298\t4940.459085\t4800.65217\t5351.745861\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Index(['ILMN_1343291', 'ILMN_1343295', 'ILMN_1651199', 'ILMN_1651209',\n", " 'ILMN_1651210', 'ILMN_1651221', 'ILMN_1651228', 'ILMN_1651229',\n", " 'ILMN_1651230', 'ILMN_1651232', 'ILMN_1651235', 'ILMN_1651236',\n", " 'ILMN_1651237', 'ILMN_1651238', 'ILMN_1651249', 'ILMN_1651253',\n", " 'ILMN_1651254', 'ILMN_1651259', 'ILMN_1651260', 'ILMN_1651262'],\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": "f4cf0170", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "28605186", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:39:47.869007Z", "iopub.status.busy": "2025-03-25T08:39:47.868876Z", "iopub.status.idle": "2025-03-25T08:39:47.871212Z", "shell.execute_reply": "2025-03-25T08:39:47.870777Z" } }, "outputs": [], "source": [ "# Reviewing the gene identifiers from the previous output\n", "# These identifiers start with \"ILMN_\" which indicates they are Illumina probe IDs\n", "# rather than standard human gene symbols (like ACTB, TP53, etc.)\n", "# Illumina IDs like ILMN_1343291 need to be mapped to human gene symbols\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "d79796f4", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "9e060be7", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:39:47.872450Z", "iopub.status.busy": "2025-03-25T08:39:47.872344Z", "iopub.status.idle": "2025-03-25T08:39:56.581722Z", "shell.execute_reply": "2025-03-25T08:39:56.581092Z" } }, "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. 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", "# 2. 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": "996c8638", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "24a605e4", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:39:56.583276Z", "iopub.status.busy": "2025-03-25T08:39:56.583026Z", "iopub.status.idle": "2025-03-25T08:39:58.137498Z", "shell.execute_reply": "2025-03-25T08:39:58.136854Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Original probe count: 47295\n", "Mapped gene count: 21459\n", "First 10 genes after mapping:\n", "Index(['A1BG', 'A1CF', 'A26C3', 'A2BP1', 'A2LD1', 'A2M', 'A2ML1', 'A3GALT2',\n", " 'A4GALT', 'A4GNT'],\n", " dtype='object', name='Gene')\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data saved to ../../output/preprocess/Duchenne_Muscular_Dystrophy/gene_data/GSE79263.csv\n" ] } ], "source": [ "# 1. Observe the gene identifiers in both dataframes\n", "# The gene expression data has identifiers like 'ILMN_1343291' in its index\n", "# The gene annotation data has a column 'ID' with similar values and a 'Symbol' column with gene symbols\n", "\n", "# 2. Get a gene mapping dataframe by extracting the ID and Symbol columns\n", "prob_col = 'ID' # Column with Illumina probe IDs\n", "gene_col = 'Symbol' # Column with gene symbols\n", "mapping_df = get_gene_mapping(gene_annotation, prob_col, gene_col)\n", "\n", "# Store the original probe count before mapping\n", "original_probe_count = len(gene_data.index)\n", "\n", "# 3. Apply the gene mapping to convert probe-level data to gene expression data\n", "try:\n", " gene_data = apply_gene_mapping(gene_data, mapping_df)\n", " \n", " # Print some info about the mapping result\n", " print(f\"Original probe count: {original_probe_count}\")\n", " print(f\"Mapped gene count: {len(gene_data.index)}\")\n", " print(\"First 10 genes after mapping:\")\n", " print(gene_data.index[:10])\n", " \n", " # Save the processed gene expression data\n", " os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", " gene_data.to_csv(out_gene_data_file)\n", " print(f\"Gene expression data saved to {out_gene_data_file}\")\n", " \n", "except Exception as e:\n", " print(f\"Error during gene mapping: {e}\")\n" ] }, { "cell_type": "markdown", "id": "35528a87", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "e29fd0ea", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:39:58.139048Z", "iopub.status.busy": "2025-03-25T08:39:58.138911Z", "iopub.status.idle": "2025-03-25T08:40:12.473816Z", "shell.execute_reply": "2025-03-25T08:40:12.473182Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data shape: (20254, 94)\n", "First few genes with their expression values after normalization:\n", " GSM2090086 GSM2090087 GSM2090088 GSM2090089 GSM2090090 \\\n", "Gene \n", "A1BG 37.186942 37.876860 36.393097 36.853984 41.675867 \n", "A1BG-AS1 18.968444 27.694886 17.843437 19.722732 18.721735 \n", "A1CF 52.382804 56.100401 54.195220 54.075285 56.799728 \n", "A2M 58.343124 31.633324 20.444786 30.120143 31.559206 \n", "A2ML1 19.408470 20.445197 17.789207 17.139441 17.707879 \n", "\n", " GSM2090091 GSM2090092 GSM2090093 GSM2090094 GSM2090095 ... \\\n", "Gene ... \n", "A1BG 36.573538 38.478149 36.868473 48.093884 45.978478 ... \n", "A1BG-AS1 19.211391 18.863080 20.727324 19.544603 17.718498 ... \n", "A1CF 59.610521 55.643605 54.333574 54.260276 53.901068 ... \n", "A2M 81.882382 61.034202 30.675956 17.208939 17.866588 ... \n", "A2ML1 17.363778 17.905866 17.688344 17.496306 18.273821 ... \n", "\n", " GSM2090170 GSM2090171 GSM2090172 GSM2090173 GSM2090174 \\\n", "Gene \n", "A1BG 42.766988 36.859218 39.232960 42.715745 39.968468 \n", "A1BG-AS1 18.315347 18.000816 18.214900 17.341939 17.553014 \n", "A1CF 53.275429 54.696810 54.751377 58.210025 55.858070 \n", "A2M 17.337431 17.385459 945.525515 801.982382 1270.198327 \n", "A2ML1 17.819060 17.819001 17.963520 17.207168 18.101247 \n", "\n", " GSM2090175 GSM2090176 GSM2090177 GSM2090178 GSM2090179 \n", "Gene \n", "A1BG 40.153471 36.419965 44.768589 37.015807 39.080027 \n", "A1BG-AS1 17.850134 18.905473 17.828391 18.151595 19.060859 \n", "A1CF 53.334349 53.159293 56.408038 53.184625 56.006998 \n", "A2M 1085.394742 616.217571 686.411421 614.427804 553.348922 \n", "A2ML1 17.860135 17.369413 17.456904 18.621235 17.508748 \n", "\n", "[5 rows x 94 columns]\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data saved to ../../output/preprocess/Duchenne_Muscular_Dystrophy/gene_data/GSE79263.csv\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Raw clinical data shape: (5, 95)\n", "Clinical features:\n", " GSM2090086 GSM2090087 GSM2090088 GSM2090089 \\\n", "Duchenne_Muscular_Dystrophy NaN NaN NaN NaN \n", "Age 80.0 78.0 NaN 79.0 \n", "\n", " GSM2090090 GSM2090091 GSM2090092 GSM2090093 \\\n", "Duchenne_Muscular_Dystrophy NaN NaN NaN NaN \n", "Age 19.0 17.0 15.0 73.0 \n", "\n", " GSM2090094 GSM2090095 ... GSM2090170 \\\n", "Duchenne_Muscular_Dystrophy 0.0 0.0 ... 1.0 \n", "Age NaN NaN ... NaN \n", "\n", " GSM2090171 GSM2090172 GSM2090173 GSM2090174 \\\n", "Duchenne_Muscular_Dystrophy 1.0 1.0 1.0 1.0 \n", "Age NaN NaN NaN NaN \n", "\n", " GSM2090175 GSM2090176 GSM2090177 GSM2090178 \\\n", "Duchenne_Muscular_Dystrophy 1.0 1.0 1.0 1.0 \n", "Age NaN NaN NaN NaN \n", "\n", " GSM2090179 \n", "Duchenne_Muscular_Dystrophy 1.0 \n", "Age NaN \n", "\n", "[2 rows x 94 columns]\n", "Clinical features saved to ../../output/preprocess/Duchenne_Muscular_Dystrophy/clinical_data/GSE79263.csv\n", "Linked data shape: (94, 20256)\n", "Linked data preview (first 5 rows, first 5 columns):\n", " Duchenne_Muscular_Dystrophy Age A1BG A1BG-AS1 A1CF\n", "GSM2090086 NaN 80.0 37.186942 18.968444 52.382804\n", "GSM2090087 NaN 78.0 37.876860 27.694886 56.100401\n", "GSM2090088 NaN NaN 36.393097 17.843437 54.195220\n", "GSM2090089 NaN 79.0 36.853984 19.722732 54.075285\n", "GSM2090090 NaN 19.0 41.675867 18.721735 56.799728\n", "Missing values before handling:\n", " Trait (Duchenne_Muscular_Dystrophy) missing: 8 out of 94\n", " Age missing: 87 out of 94\n", " Genes with >20% missing: 0\n", " Samples with >5% missing genes: 0\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Data shape after handling missing values: (86, 20256)\n", "For the feature 'Duchenne_Muscular_Dystrophy', the least common label is '0.0' with 36 occurrences. This represents 41.86% of the dataset.\n", "The distribution of the feature 'Duchenne_Muscular_Dystrophy' in this dataset is fine.\n", "\n", "Quartiles for 'Age':\n", " 25%: nan\n", " 50% (Median): nan\n", " 75%: nan\n", "Min: nan\n", "Max: nan\n", "The distribution of the feature 'Age' in this dataset is fine.\n", "\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data saved to ../../output/preprocess/Duchenne_Muscular_Dystrophy/GSE79263.csv\n" ] } ], "source": [ "# 1. Normalize gene symbols in the gene expression data\n", "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"Normalized gene data shape: {normalized_gene_data.shape}\")\n", "print(\"First few genes with their expression values after normalization:\")\n", "print(normalized_gene_data.head())\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", "# Define placeholder for convert_gender since it wasn't needed (gender_row is None)\n", "convert_gender = None\n", "\n", "# 2. Extract clinical features directly from the matrix file\n", "try:\n", " # Get the file paths for the matrix file to extract clinical data\n", " _, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", " \n", " # Get raw clinical data from the matrix file\n", " _, clinical_raw = get_background_and_clinical_data(matrix_file)\n", " \n", " # Verify clinical data structure\n", " print(\"Raw clinical data shape:\", clinical_raw.shape)\n", " \n", " # Extract clinical features using the defined conversion functions\n", " clinical_features = geo_select_clinical_features(\n", " clinical_df=clinical_raw,\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", " print(\"Clinical features:\")\n", " print(clinical_features)\n", " \n", " # Save clinical features to file\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " clinical_features.to_csv(out_clinical_data_file)\n", " print(f\"Clinical features saved to {out_clinical_data_file}\")\n", " \n", " # 3. Link clinical and genetic data\n", " linked_data = geo_link_clinical_genetic_data(clinical_features, normalized_gene_data)\n", " print(f\"Linked data shape: {linked_data.shape}\")\n", " print(\"Linked data preview (first 5 rows, first 5 columns):\")\n", " print(linked_data.iloc[:5, :5])\n", " \n", " # 4. Handle missing values\n", " print(\"Missing 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", " 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", " # 5. 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", " # 6. 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=True, \n", " is_trait_available=True, \n", " is_biased=is_trait_biased, \n", " df=cleaned_data,\n", " note=\"Dataset contains gene expression data comparing Duchenne muscular dystrophy vs healthy samples.\"\n", " )\n", " \n", " # 7. 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\")\n", " \n", "except Exception as e:\n", " print(f\"Error processing data: {e}\")\n", " # Handle the error case by still recording cohort info\n", " 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=False, # Mark as not available due to processing issues\n", " is_biased=True, \n", " df=pd.DataFrame(), # Empty dataframe\n", " note=f\"Error processing data: {str(e)}\"\n", " )\n", " print(\"Data was determined to be unusable 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 }