{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "f1ad5b3e", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:39:18.841544Z", "iopub.status.busy": "2025-03-25T08:39:18.841440Z", "iopub.status.idle": "2025-03-25T08:39:19.002128Z", "shell.execute_reply": "2025-03-25T08:39:19.001767Z" } }, "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 = \"GSE13608\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Duchenne_Muscular_Dystrophy\"\n", "in_cohort_dir = \"../../input/GEO/Duchenne_Muscular_Dystrophy/GSE13608\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Duchenne_Muscular_Dystrophy/GSE13608.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Duchenne_Muscular_Dystrophy/gene_data/GSE13608.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Duchenne_Muscular_Dystrophy/clinical_data/GSE13608.csv\"\n", "json_path = \"../../output/preprocess/Duchenne_Muscular_Dystrophy/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "2f3d6fe7", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "c29eb9d2", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:39:19.003532Z", "iopub.status.busy": "2025-03-25T08:39:19.003395Z", "iopub.status.idle": "2025-03-25T08:39:19.167490Z", "shell.execute_reply": "2025-03-25T08:39:19.167169Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Skeletal muscle biopsies of patients with myotonic dystrophy (DM) and non-DM neuro-muscular disorders\"\n", "!Series_summary\t\"Skeletal muscle biopsies from DM1, DM2, idiopathic DM (DMx), and non-DM NMD patients were compared to those from normal individuals, with focus on MEF2 and MEF2-related genes.\"\n", "!Series_summary\t\"\"\n", "!Series_summary\t\"Keywords: 7 diseases and 2 normal (fetal and adult) groups\"\n", "!Series_overall_design\t\"Skeletal muscle biopsies from 10 DM1 biopsies, 20 DM2 biopsies, 16 DMx (DM-like, no DMPK or ZNF9 expansion), 5 BMD (Becker Muscular Dystrophy), 1 MC-AD (Myotonia Congenita-Autosomal Dominant), 3 DMD (Duchenne Muscular Dystrophy), 4 TMD (Tibial Muscular Dystrophy), 3 Normal Fetal and 6 Normal individuals\"\n", "Sample Characteristics Dictionary:\n", "{0: ['biopsy site: Biceps brachii', 'biopsy site: Deltoid', 'biopsy site: unknown', 'biopsy site: Quadriceps', 'biopsy site: Vastus lateralis', 'biopsy site: Tibialis anterior', 'biopsy site: Gastrocnemius', 'biopsy site: Triceps brachii', 'biopsy site: Extensor hallucis/Digitorum longus'], 1: ['DM1 patient', 'DM2 patient', 'DMX patient', 'Normal adult patient', 'Normal fetus patient', 'Baker Myotonic Dystrophy patient', 'Duchenne Muscular Dystrophy patient', 'Tibial Muscular Dystropy patient', 'Myotonia Congenita Autosomal Dominant patient'], 2: ['age unknown', 'age 55', 'age 54', 'age 25', 'age 29', 'age 21', 'age 71', 'age 39', 'age 69', 'age 68', 'age 32', 'age 47', 'age 57', 'age 43', 'age 37', 'age 65', 'age 42', 'age 50', 'age 51', 'age 58', 'age 28', 'age 49', 'age 75', 'age 73', 'age 53', 'age 36', 'age 46', 'age 48', 'age 61', 'age 85'], 3: ['Gender: F', 'Gender: M', 'Gender M/F pool']}\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": "bb0094a8", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "b320c3cb", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:39:19.168733Z", "iopub.status.busy": "2025-03-25T08:39:19.168619Z", "iopub.status.idle": "2025-03-25T08:39:19.195323Z", "shell.execute_reply": "2025-03-25T08:39:19.195013Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Preview of selected clinical features:\n", "{0: [0.0, nan, 0.0], 1: [0.0, 55.0, 1.0], 2: [0.0, 54.0, nan], 3: [0.0, 25.0, nan], 4: [0.0, 29.0, nan], 5: [0.0, 21.0, nan], 6: [1.0, 71.0, nan], 7: [0.0, 39.0, nan], 8: [0.0, 69.0, nan], 9: [nan, 68.0, nan], 10: [nan, 32.0, nan], 11: [nan, 47.0, nan], 12: [nan, 57.0, nan], 13: [nan, 43.0, nan], 14: [nan, 37.0, nan], 15: [nan, 65.0, nan], 16: [nan, 42.0, nan], 17: [nan, 50.0, nan], 18: [nan, 51.0, nan], 19: [nan, 58.0, nan], 20: [nan, 28.0, nan], 21: [nan, 49.0, nan], 22: [nan, 75.0, nan], 23: [nan, 73.0, nan], 24: [nan, 53.0, nan], 25: [nan, 36.0, nan], 26: [nan, 46.0, nan], 27: [nan, 48.0, nan], 28: [nan, 61.0, nan], 29: [nan, 85.0, nan]}\n", "Clinical data saved to ../../output/preprocess/Duchenne_Muscular_Dystrophy/clinical_data/GSE13608.csv\n" ] } ], "source": [ "import pandas as pd\n", "import os\n", "import json\n", "from typing import Callable, Optional, Dict, Any\n", "\n", "# 1. Gene Expression Data Availability\n", "# Based on the background information, this dataset includes genomic expression profiles from muscle biopsies\n", "is_gene_available = True # This dataset likely contains gene expression data for multiple muscle disorders\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "\n", "# Trait row identification: Row 1 contains disease information\n", "trait_row = 1 # \"DM1 patient\", \"DMD patient\", etc.\n", "\n", "# Age row identification: Row 2 contains age information\n", "age_row = 2 # \"age unknown\", \"age 55\", etc.\n", "\n", "# Gender row identification: Row 3 contains gender information\n", "gender_row = 3 # \"Gender: F\", \"Gender: M\", etc.\n", "\n", "# 2.2 Data Type Conversion Functions\n", "\n", "def convert_trait(value: str) -> int:\n", " \"\"\"Convert trait value to binary (0 for non-DMD, 1 for DMD).\"\"\"\n", " if value is None:\n", " return None\n", " value = value.lower() if isinstance(value, str) else str(value).lower()\n", " if \"duchenne muscular dystrophy\" in value or \"dmd patient\" in value:\n", " return 1\n", " else:\n", " return 0\n", "\n", "def convert_age(value: str) -> Optional[float]:\n", " \"\"\"Extract age as a continuous value.\"\"\"\n", " if value is None:\n", " return None\n", " value = value.lower() if isinstance(value, str) else str(value).lower()\n", " if \"age unknown\" in value:\n", " return None\n", " elif \"age\" in value:\n", " try:\n", " # Extract number after \"age\" keyword\n", " age_str = value.split(\"age\")[1].strip()\n", " return float(age_str)\n", " except (ValueError, IndexError):\n", " return None\n", " return None\n", "\n", "def convert_gender(value: str) -> Optional[int]:\n", " \"\"\"Convert gender to binary (0 for female, 1 for male).\"\"\"\n", " if value is None:\n", " return None\n", " value = value.lower() if isinstance(value, str) else str(value).lower()\n", " if \"gender: f\" in value:\n", " return 0\n", " elif \"gender: m\" in value:\n", " return 1\n", " elif \"gender m/f pool\" in value:\n", " return None # Mixed samples can't be assigned to a specific gender\n", " return None\n", "\n", "# Helper function used by geo_select_clinical_features\n", "def get_feature_data(df, row_idx, feature_name, convert_func):\n", " \"\"\"Extract and convert feature data from a row in the DataFrame.\"\"\"\n", " if row_idx is None:\n", " return pd.DataFrame({feature_name: []})\n", " \n", " values = df[row_idx].tolist()\n", " converted_values = [convert_func(val) for val in values]\n", " return pd.DataFrame({feature_name: converted_values})\n", "\n", "# 3. Save Metadata - Initial Filtering\n", "is_trait_available = (trait_row is not None)\n", "validate_and_save_cohort_info(\n", " is_final=False,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=is_gene_available,\n", " is_trait_available=is_trait_available\n", ")\n", "\n", "# 4. Clinical Feature Extraction\n", "if trait_row is not None:\n", " # Create clinical_data from the sample characteristics dictionary provided\n", " # Sample characteristics dictionary from previous step output\n", " char_dict = {\n", " 0: ['biopsy site: Biceps brachii', 'biopsy site: Deltoid', 'biopsy site: unknown', 'biopsy site: Quadriceps', \n", " 'biopsy site: Vastus lateralis', 'biopsy site: Tibialis anterior', 'biopsy site: Gastrocnemius', \n", " 'biopsy site: Triceps brachii', 'biopsy site: Extensor hallucis/Digitorum longus'],\n", " 1: ['DM1 patient', 'DM2 patient', 'DMX patient', 'Normal adult patient', 'Normal fetus patient', \n", " 'Baker Myotonic Dystrophy patient', 'Duchenne Muscular Dystrophy patient', \n", " 'Tibial Muscular Dystropy patient', 'Myotonia Congenita Autosomal Dominant patient'],\n", " 2: ['age unknown', 'age 55', 'age 54', 'age 25', 'age 29', 'age 21', 'age 71', 'age 39', 'age 69', \n", " 'age 68', 'age 32', 'age 47', 'age 57', 'age 43', 'age 37', 'age 65', 'age 42', 'age 50', \n", " 'age 51', 'age 58', 'age 28', 'age 49', 'age 75', 'age 73', 'age 53', 'age 36', 'age 46', \n", " 'age 48', 'age 61', 'age 85'],\n", " 3: ['Gender: F', 'Gender: M', 'Gender M/F pool']\n", " }\n", " \n", " # Convert dictionary to proper format for geo_select_clinical_features\n", " clinical_data = pd.DataFrame.from_dict(char_dict, orient='index')\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 DataFrame\n", " preview = preview_df(selected_clinical_df)\n", " print(\"Preview of selected clinical features:\")\n", " print(preview)\n", " \n", " # Save the clinical data\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " selected_clinical_df.to_csv(out_clinical_data_file, index=False)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "de6cc4cd", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "489376a0", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:39:19.196494Z", "iopub.status.busy": "2025-03-25T08:39:19.196384Z", "iopub.status.idle": "2025-03-25T08:39:19.457158Z", "shell.execute_reply": "2025-03-25T08:39:19.456788Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Found data marker at line 63\n", "Header line: \"ID_REF\"\t\"GSM343029\"\t\"GSM343030\"\t\"GSM343031\"\t\"GSM343032\"\t\"GSM343033\"\t\"GSM343034\"\t\"GSM343035\"\t\"GSM343036\"\t\"GSM343037\"\t\"GSM343038\"\t\"GSM343039\"\t\"GSM343040\"\t\"GSM343041\"\t\"GSM343042\"\t\"GSM343043\"\t\"GSM343044\"\t\"GSM343045\"\t\"GSM343046\"\t\"GSM343047\"\t\"GSM343048\"\t\"GSM343049\"\t\"GSM343050\"\t\"GSM343051\"\t\"GSM343052\"\t\"GSM343053\"\t\"GSM343054\"\t\"GSM343055\"\t\"GSM343056\"\t\"GSM343057\"\t\"GSM343058\"\t\"GSM343059\"\t\"GSM343060\"\t\"GSM343061\"\t\"GSM343062\"\t\"GSM343063\"\t\"GSM343064\"\t\"GSM343065\"\t\"GSM343066\"\t\"GSM343067\"\t\"GSM343068\"\t\"GSM343069\"\t\"GSM343070\"\t\"GSM343071\"\t\"GSM343072\"\t\"GSM343073\"\t\"GSM343074\"\t\"GSM343075\"\t\"GSM343076\"\t\"GSM343077\"\t\"GSM343078\"\t\"GSM343079\"\t\"GSM343080\"\t\"GSM343081\"\t\"GSM343082\"\t\"GSM343083\"\t\"GSM343084\"\t\"GSM343085\"\t\"GSM343086\"\t\"GSM343087\"\t\"GSM343088\"\t\"GSM343089\"\t\"GSM343090\"\t\"GSM343091\"\t\"GSM343092\"\t\"GSM343093\"\t\"GSM343094\"\t\"GSM343095\"\t\"GSM343096\"\n", "First data line: \"1007_s_at\"\t483\t446.71\t471.33\t554.88\t265.14\t537.91\t305.4\t400.95\t387.56\t434.66\t432.39\t282.27\t385.39\t503.47\t410.8\t318.82\t372.21\t448.06\t353.65\t382.19\t304.73\t486.95\t519.98\t469.47\t415.87\t475.22\t479.75\t327.15\t417.14\t526.2\t293.86\t385.38\t361.95\t324.6\t581.17\t293.11\t523.99\t410.41\t324.25\t359.47\t356.68\t252.94\t319\t418.72\t455.18\t264.06\t506.47\t947.63\t457.32\t434.94\t376.7\t365.32\t924.86\t751.82\t856.69\t494.05\t471\t445.15\t478.38\t535.23\t564.4\t497.93\t564.13\t495.51\t485\t493.99\t606.13\t426.88\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Index(['1007_s_at', '1053_at', '117_at', '121_at', '1255_g_at', '1294_at',\n", " '1316_at', '1320_at', '1405_i_at', '1431_at', '1438_at', '1487_at',\n", " '1494_f_at', '1552256_a_at', '1552257_a_at', '1552258_at', '1552261_at',\n", " '1552263_at', '1552264_a_at', '1552266_at'],\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": "2064f698", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "143426b9", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:39:19.458475Z", "iopub.status.busy": "2025-03-25T08:39:19.458353Z", "iopub.status.idle": "2025-03-25T08:39:19.460295Z", "shell.execute_reply": "2025-03-25T08:39:19.459976Z" } }, "outputs": [], "source": [ "# Looking at the gene IDs from the snapshot, these appear to be probe IDs from an Affymetrix microarray\n", "# (like \"1007_s_at\", \"1053_at\", etc.). These are not standard human gene symbols.\n", "# They need to be mapped to gene symbols for better interpretation and analysis.\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "9c0382ef", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "d7808f71", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:39:19.461455Z", "iopub.status.busy": "2025-03-25T08:39:19.461351Z", "iopub.status.idle": "2025-03-25T08:39:24.257515Z", "shell.execute_reply": "2025-03-25T08:39:24.257139Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene annotation preview:\n", "{'ID': ['1007_s_at', '1053_at', '117_at', '121_at', '1255_g_at'], 'GB_ACC': ['U48705', 'M87338', 'X51757', 'X69699', 'L36861'], 'SPOT_ID': [nan, nan, nan, nan, nan], 'Species Scientific Name': ['Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens'], 'Annotation Date': ['Oct 6, 2014', 'Oct 6, 2014', 'Oct 6, 2014', 'Oct 6, 2014', 'Oct 6, 2014'], 'Sequence Type': ['Exemplar sequence', 'Exemplar sequence', 'Exemplar sequence', 'Exemplar sequence', 'Exemplar sequence'], 'Sequence Source': ['Affymetrix Proprietary Database', 'GenBank', 'Affymetrix Proprietary Database', 'GenBank', 'Affymetrix Proprietary Database'], 'Target Description': ['U48705 /FEATURE=mRNA /DEFINITION=HSU48705 Human receptor tyrosine kinase DDR gene, complete cds', 'M87338 /FEATURE= /DEFINITION=HUMA1SBU Human replication factor C, 40-kDa subunit (A1) mRNA, complete cds', \"X51757 /FEATURE=cds /DEFINITION=HSP70B Human heat-shock protein HSP70B' gene\", 'X69699 /FEATURE= /DEFINITION=HSPAX8A H.sapiens Pax8 mRNA', 'L36861 /FEATURE=expanded_cds /DEFINITION=HUMGCAPB Homo sapiens guanylate cyclase activating protein (GCAP) gene exons 1-4, complete cds'], 'Representative Public ID': ['U48705', 'M87338', 'X51757', 'X69699', 'L36861'], 'Gene Title': ['discoidin domain receptor tyrosine kinase 1 /// microRNA 4640', 'replication factor C (activator 1) 2, 40kDa', \"heat shock 70kDa protein 6 (HSP70B')\", 'paired box 8', 'guanylate cyclase activator 1A (retina)'], 'Gene Symbol': ['DDR1 /// MIR4640', 'RFC2', 'HSPA6', 'PAX8', 'GUCA1A'], 'ENTREZ_GENE_ID': ['780 /// 100616237', '5982', '3310', '7849', '2978'], 'RefSeq Transcript ID': ['NM_001202521 /// NM_001202522 /// NM_001202523 /// NM_001954 /// NM_013993 /// NM_013994 /// NR_039783 /// XM_005249385 /// XM_005249386 /// XM_005249387 /// XM_005249389 /// XM_005272873 /// XM_005272874 /// XM_005272875 /// XM_005272877 /// XM_005275027 /// XM_005275028 /// XM_005275030 /// XM_005275031 /// XM_005275162 /// XM_005275163 /// XM_005275164 /// XM_005275166 /// XM_005275457 /// XM_005275458 /// XM_005275459 /// XM_005275461 /// XM_006715185 /// XM_006715186 /// XM_006715187 /// XM_006715188 /// XM_006715189 /// XM_006715190 /// XM_006725501 /// XM_006725502 /// XM_006725503 /// XM_006725504 /// XM_006725505 /// XM_006725506 /// XM_006725714 /// XM_006725715 /// XM_006725716 /// XM_006725717 /// XM_006725718 /// XM_006725719 /// XM_006725720 /// XM_006725721 /// XM_006725722 /// XM_006725827 /// XM_006725828 /// XM_006725829 /// XM_006725830 /// XM_006725831 /// XM_006725832 /// XM_006726017 /// XM_006726018 /// XM_006726019 /// XM_006726020 /// XM_006726021 /// XM_006726022 /// XR_427836 /// XR_430858 /// XR_430938 /// XR_430974 /// XR_431015', 'NM_001278791 /// NM_001278792 /// NM_001278793 /// NM_002914 /// NM_181471 /// XM_006716080', 'NM_002155', 'NM_003466 /// NM_013951 /// NM_013952 /// NM_013953 /// NM_013992', 'NM_000409 /// XM_006715073'], 'Gene Ontology Biological Process': ['0001558 // regulation of cell growth // inferred from electronic annotation /// 0001952 // regulation of cell-matrix adhesion // inferred from electronic annotation /// 0006468 // protein phosphorylation // inferred from electronic annotation /// 0007155 // cell adhesion // traceable author statement /// 0007169 // transmembrane receptor protein tyrosine kinase signaling pathway // inferred from electronic annotation /// 0007565 // female pregnancy // inferred from electronic annotation /// 0007566 // embryo implantation // inferred from electronic annotation /// 0007595 // lactation // inferred from electronic annotation /// 0008285 // negative regulation of cell proliferation // inferred from electronic annotation /// 0010715 // regulation of extracellular matrix disassembly // inferred from mutant phenotype /// 0014909 // smooth muscle cell migration // inferred from mutant phenotype /// 0016310 // phosphorylation // inferred from electronic annotation /// 0018108 // peptidyl-tyrosine phosphorylation // inferred from electronic annotation /// 0030198 // extracellular matrix organization // traceable author statement /// 0038063 // collagen-activated tyrosine kinase receptor signaling pathway // inferred from direct assay /// 0038063 // collagen-activated tyrosine kinase receptor signaling pathway // inferred from mutant phenotype /// 0038083 // peptidyl-tyrosine autophosphorylation // inferred from direct assay /// 0043583 // ear development // inferred from electronic annotation /// 0044319 // wound healing, spreading of cells // inferred from mutant phenotype /// 0046777 // protein autophosphorylation // inferred from direct assay /// 0060444 // branching involved in mammary gland duct morphogenesis // inferred from electronic annotation /// 0060749 // mammary gland alveolus development // inferred from electronic annotation /// 0061302 // smooth muscle cell-matrix adhesion // inferred from mutant phenotype', '0000278 // mitotic cell cycle // traceable author statement /// 0000722 // telomere maintenance via recombination // traceable author statement /// 0000723 // telomere maintenance // traceable author statement /// 0006260 // DNA replication // traceable author statement /// 0006271 // DNA strand elongation involved in DNA replication // traceable author statement /// 0006281 // DNA repair // traceable author statement /// 0006283 // transcription-coupled nucleotide-excision repair // traceable author statement /// 0006289 // nucleotide-excision repair // traceable author statement /// 0006297 // nucleotide-excision repair, DNA gap filling // traceable author statement /// 0015979 // photosynthesis // inferred from electronic annotation /// 0015995 // chlorophyll biosynthetic process // inferred from electronic annotation /// 0032201 // telomere maintenance via semi-conservative replication // traceable author statement', '0000902 // cell morphogenesis // inferred from electronic annotation /// 0006200 // ATP catabolic process // inferred from direct assay /// 0006950 // response to stress // inferred from electronic annotation /// 0006986 // response to unfolded protein // traceable author statement /// 0034605 // cellular response to heat // inferred from direct assay /// 0042026 // protein refolding // inferred from direct assay /// 0070370 // cellular heat acclimation // inferred from mutant phenotype', '0001655 // urogenital system development // inferred from sequence or structural similarity /// 0001656 // metanephros development // inferred from electronic annotation /// 0001658 // branching involved in ureteric bud morphogenesis // inferred from expression pattern /// 0001822 // kidney development // inferred from expression pattern /// 0001823 // mesonephros development // inferred from sequence or structural similarity /// 0003337 // mesenchymal to epithelial transition involved in metanephros morphogenesis // inferred from expression pattern /// 0006351 // transcription, DNA-templated // inferred from direct assay /// 0006355 // regulation of transcription, DNA-templated // inferred from electronic annotation /// 0007275 // multicellular organismal development // inferred from electronic annotation /// 0007417 // central nervous system development // inferred from expression pattern /// 0009653 // anatomical structure morphogenesis // traceable author statement /// 0030154 // cell differentiation // inferred from electronic annotation /// 0030878 // thyroid gland development // inferred from expression pattern /// 0030878 // thyroid gland development // inferred from mutant phenotype /// 0038194 // thyroid-stimulating hormone signaling pathway // traceable author statement /// 0039003 // pronephric field specification // inferred from sequence or structural similarity /// 0042472 // inner ear morphogenesis // inferred from sequence or structural similarity /// 0042981 // regulation of apoptotic process // inferred from sequence or structural similarity /// 0045893 // positive regulation of transcription, DNA-templated // inferred from direct assay /// 0045893 // positive regulation of transcription, DNA-templated // inferred from sequence or structural similarity /// 0045944 // positive regulation of transcription from RNA polymerase II promoter // inferred from direct assay /// 0048793 // pronephros development // inferred from sequence or structural similarity /// 0071371 // cellular response to gonadotropin stimulus // inferred from direct assay /// 0071599 // otic vesicle development // inferred from expression pattern /// 0072050 // S-shaped body morphogenesis // inferred from electronic annotation /// 0072073 // kidney epithelium development // inferred from electronic annotation /// 0072108 // positive regulation of mesenchymal to epithelial transition involved in metanephros morphogenesis // inferred from sequence or structural similarity /// 0072164 // mesonephric tubule development // inferred from electronic annotation /// 0072207 // metanephric epithelium development // inferred from expression pattern /// 0072221 // metanephric distal convoluted tubule development // inferred from sequence or structural similarity /// 0072278 // metanephric comma-shaped body morphogenesis // inferred from expression pattern /// 0072284 // metanephric S-shaped body morphogenesis // inferred from expression pattern /// 0072289 // metanephric nephron tubule formation // inferred from sequence or structural similarity /// 0072305 // negative regulation of mesenchymal cell apoptotic process involved in metanephric nephron morphogenesis // inferred from sequence or structural similarity /// 0072307 // regulation of metanephric nephron tubule epithelial cell differentiation // inferred from sequence or structural similarity /// 0090190 // positive regulation of branching involved in ureteric bud morphogenesis // inferred from sequence or structural similarity /// 1900212 // negative regulation of mesenchymal cell apoptotic process involved in metanephros development // inferred from sequence or structural similarity /// 1900215 // negative regulation of apoptotic process involved in metanephric collecting duct development // inferred from sequence or structural similarity /// 1900218 // negative regulation of apoptotic process involved in metanephric nephron tubule development // inferred from sequence or structural similarity /// 2000594 // positive regulation of metanephric DCT cell differentiation // inferred from sequence or structural similarity /// 2000611 // positive regulation of thyroid hormone generation // inferred from mutant phenotype /// 2000612 // regulation of thyroid-stimulating hormone secretion // inferred from mutant phenotype', '0007165 // signal transduction // non-traceable author statement /// 0007601 // visual perception // inferred from electronic annotation /// 0007602 // phototransduction // inferred from electronic annotation /// 0007603 // phototransduction, visible light // traceable author statement /// 0016056 // rhodopsin mediated signaling pathway // traceable author statement /// 0022400 // regulation of rhodopsin mediated signaling pathway // traceable author statement /// 0030828 // positive regulation of cGMP biosynthetic process // inferred from electronic annotation /// 0031282 // regulation of guanylate cyclase activity // inferred from electronic annotation /// 0031284 // positive regulation of guanylate cyclase activity // inferred from electronic annotation /// 0050896 // response to stimulus // inferred from electronic annotation'], 'Gene Ontology Cellular Component': ['0005576 // extracellular region // inferred from electronic annotation /// 0005615 // extracellular space // inferred from direct assay /// 0005886 // plasma membrane // traceable author statement /// 0005887 // integral component of plasma membrane // traceable author statement /// 0016020 // membrane // inferred from electronic annotation /// 0016021 // integral component of membrane // inferred from electronic annotation /// 0043235 // receptor complex // inferred from direct assay /// 0070062 // extracellular vesicular exosome // inferred from direct assay', '0005634 // nucleus // inferred from electronic annotation /// 0005654 // nucleoplasm // traceable author statement /// 0005663 // DNA replication factor C complex // inferred from direct assay', '0005737 // cytoplasm // inferred from direct assay /// 0005814 // centriole // inferred from direct assay /// 0005829 // cytosol // inferred from direct assay /// 0008180 // COP9 signalosome // inferred from direct assay /// 0070062 // extracellular vesicular exosome // inferred from direct assay /// 0072562 // blood microparticle // inferred from direct assay', '0005634 // nucleus // inferred from direct assay /// 0005654 // nucleoplasm // inferred from sequence or structural similarity /// 0005730 // nucleolus // inferred from direct assay', '0001750 // photoreceptor outer segment // inferred from electronic annotation /// 0001917 // photoreceptor inner segment // inferred from electronic annotation /// 0005578 // proteinaceous extracellular matrix // inferred from electronic annotation /// 0005886 // plasma membrane // inferred from direct assay /// 0016020 // membrane // inferred from electronic annotation /// 0097381 // photoreceptor disc membrane // traceable author statement'], 'Gene Ontology Molecular Function': ['0000166 // nucleotide binding // inferred from electronic annotation /// 0004672 // protein kinase activity // inferred from electronic annotation /// 0004713 // protein tyrosine kinase activity // inferred from electronic annotation /// 0004714 // transmembrane receptor protein tyrosine kinase activity // traceable author statement /// 0005515 // protein binding // inferred from physical interaction /// 0005518 // collagen binding // inferred from direct assay /// 0005518 // collagen binding // inferred from mutant phenotype /// 0005524 // ATP binding // inferred from electronic annotation /// 0016301 // kinase activity // inferred from electronic annotation /// 0016740 // transferase activity // inferred from electronic annotation /// 0016772 // transferase activity, transferring phosphorus-containing groups // inferred from electronic annotation /// 0038062 // protein tyrosine kinase collagen receptor activity // inferred from direct assay /// 0046872 // metal ion binding // inferred from electronic annotation', '0000166 // nucleotide binding // inferred from electronic annotation /// 0003677 // DNA binding // inferred from electronic annotation /// 0005515 // protein binding // inferred from physical interaction /// 0005524 // ATP binding // inferred from electronic annotation /// 0016851 // magnesium chelatase activity // inferred from electronic annotation /// 0017111 // nucleoside-triphosphatase activity // inferred from electronic annotation', '0000166 // nucleotide binding // inferred from electronic annotation /// 0005524 // ATP binding // inferred from electronic annotation /// 0019899 // enzyme binding // inferred from physical interaction /// 0031072 // heat shock protein binding // inferred from physical interaction /// 0042623 // ATPase activity, coupled // inferred from direct assay /// 0051082 // unfolded protein binding // inferred from direct assay', '0000979 // RNA polymerase II core promoter sequence-specific DNA binding // inferred from direct assay /// 0003677 // DNA binding // inferred from direct assay /// 0003677 // DNA binding // inferred from mutant phenotype /// 0003700 // sequence-specific DNA binding transcription factor activity // inferred from direct assay /// 0004996 // thyroid-stimulating hormone receptor activity // traceable author statement /// 0005515 // protein binding // inferred from physical interaction /// 0044212 // transcription regulatory region DNA binding // inferred from direct assay', '0005509 // calcium ion binding // inferred from electronic annotation /// 0008048 // calcium sensitive guanylate cyclase activator activity // inferred from electronic annotation /// 0030249 // guanylate cyclase regulator activity // inferred from electronic annotation /// 0046872 // metal ion binding // inferred from electronic annotation']}\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": "19bafe8e", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "0bb54257", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:39:24.258976Z", "iopub.status.busy": "2025-03-25T08:39:24.258685Z", "iopub.status.idle": "2025-03-25T08:39:25.258388Z", "shell.execute_reply": "2025-03-25T08:39:25.258010Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene mapping preview:\n", "{'ID': ['1007_s_at', '1053_at', '117_at', '121_at', '1255_g_at'], 'Gene': ['DDR1 /// MIR4640', 'RFC2', 'HSPA6', 'PAX8', 'GUCA1A']}\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene expression data preview (after mapping):\n", "Number of genes: 21278\n", "Number of samples: 68\n", "{'GSM343029': [125.24, 115.75, 93.97999999999999, 2135.54, 156.68], 'GSM343030': [109.31, 168.38, 134.31, 1467.21, 67.45], 'GSM343031': [113.71, 174.9, 119.44, 1383.6599999999999, 93.9], 'GSM343032': [107.14, 124.05, 105.66999999999999, 1574.3000000000002, 140.36], 'GSM343033': [102.77, 151.74, 117.64, 1700.99, 86.04], 'GSM343034': [100.74, 150.76, 111.8, 1631.14, 146.31], 'GSM343035': [99.52, 140.66, 105.67, 1924.62, 166.86], 'GSM343036': [110.14, 186.51, 114.62, 1101.58, 77.69], 'GSM343037': [119.63, 141.71, 149.63, 1820.77, 140.92], 'GSM343038': [113.36, 160.39, 153.93, 1790.31, 116.04], 'GSM343039': [94.31, 153.6, 108.09, 1621.31, 98.17], 'GSM343040': [108.13, 160.95, 114.18, 1736.69, 74.1], 'GSM343041': [116.89, 170.59, 105.55, 1594.04, 100.08], 'GSM343042': [111.56, 129.37, 100.34, 1380.74, 62.45], 'GSM343043': [103.87, 169.32, 98.57, 1625.41, 83.63], 'GSM343044': [125.91, 163.58, 125.80000000000001, 1271.5700000000002, 95.35], 'GSM343045': [113.9, 152.71, 107.44, 1538.7099999999998, 85.46], 'GSM343046': [114.36, 128.41, 97.49000000000001, 1926.2, 146.27], 'GSM343047': [114.13, 158.87, 115.29, 1832.6299999999999, 84.01], 'GSM343048': [105.11, 151.97, 122.72, 1589.7099999999998, 48.75], 'GSM343049': [115.07, 165.41, 115.72, 1800.1399999999999, 113.44], 'GSM343050': [128.47, 170.42, 128.28, 1882.8, 141.87], 'GSM343051': [101.45, 128.77, 103.68, 1540.5, 73.47], 'GSM343052': [100.59, 142.82, 105.61, 1428.38, 94.04], 'GSM343053': [98.29, 140.62, 108.18, 1864.08, 88.98], 'GSM343054': [109.38, 147.48, 118.57, 1945.44, 95.03], 'GSM343055': [120.92, 153.83, 117.72, 1519.45, 87.8], 'GSM343056': [121.7, 169.26, 113.28, 1328.6499999999999, 112.63], 'GSM343057': [97.8, 176.45, 116.42, 1344.65, 122.18], 'GSM343058': [100.65, 143.27, 124.32, 1531.1799999999998, 80.75], 'GSM343059': [117.46, 161.03, 121.32, 1308.12, 73.66], 'GSM343060': [99.61, 138.33, 101.6, 1359.58, 71.32], 'GSM343061': [99.38, 138.73, 104.16, 2388.5400000000004, 91.26], 'GSM343062': [99.87, 146.06, 105.75, 1251.8600000000001, 94.7], 'GSM343063': [94.37, 143.66, 107.57, 1926.7, 78.49], 'GSM343064': [95.21, 138.17, 103.49, 1331.59, 112.09], 'GSM343065': [104.23, 124.32, 98.91, 1760.7, 110.27], 'GSM343066': [103.75, 132.91, 107.86, 1769.81, 119.56], 'GSM343067': [113.47, 193.61, 125.15, 1850.26, 72.53], 'GSM343068': [97.6, 159.3, 96.83, 1336.51, 76.26], 'GSM343069': [100.65, 144.93, 94.88, 1641.4, 83.36], 'GSM343070': [113.43, 134.51, 99.81, 1344.01, 80.96], 'GSM343071': [111.39, 151.45, 126.05000000000001, 975.08, 94.84], 'GSM343072': [101.43, 139.37, 112.24000000000001, 1326.69, 75.99], 'GSM343073': [113.94, 165.37, 111.32, 1240.56, 63.09], 'GSM343074': [103.98, 154.67, 97.92, 1927.75, 82.11], 'GSM343075': [97.06, 114.7, 106.84, 1369.73, 65.81], 'GSM343076': [108.49, 115.69, 93.38, 1471.0500000000002, 70.62], 'GSM343077': [118.06, 158.41, 137.32, 816.86, 43.82], 'GSM343078': [109.9, 164.41, 123.98, 815.4599999999999, 50.68], 'GSM343079': [138.12, 206.82, 151.26, 515.1, 45.29], 'GSM343080': [118.31, 134.78, 116.77000000000001, 1137.9, 74.3], 'GSM343081': [131.9, 89.91, 80.98, 2193.8100000000004, 119.14], 'GSM343082': [165.74, 106.35, 89.7, 2181.9900000000002, 102.35], 'GSM343083': [139.79, 104.43, 83.44, 1974.31, 192.18], 'GSM343084': [98.52, 138.78, 114.92, 2959.77, 114.99], 'GSM343085': [109.59, 144.49, 86.59, 1906.79, 141.09], 'GSM343086': [98.78, 146.57, 110.79, 2559.25, 80.76], 'GSM343087': [104.37, 144.49, 110.87, 1937.06, 110.65], 'GSM343088': [95.92, 117.62, 90.58000000000001, 2895.52, 193.4], 'GSM343089': [113.77, 133.32, 82.22, 3777.8, 144.23], 'GSM343090': [110.98, 146.37, 115.93, 3264.79, 191.21], 'GSM343091': [120.7, 120.06, 81.67, 2687.43, 185.32], 'GSM343092': [115.13, 171.98, 104.6, 974.38, 78.36], 'GSM343093': [118.34, 147.19, 111.89, 2940.72, 155.9], 'GSM343094': [103.11, 134.13, 122.13, 1441.71, 87.1], 'GSM343095': [103.51, 131.04, 106.91, 1965.6100000000001, 104.06], 'GSM343096': [103.1, 176.26, 136.76999999999998, 2336.7599999999998, 104.5]}\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene expression data saved to ../../output/preprocess/Duchenne_Muscular_Dystrophy/gene_data/GSE13608.csv\n" ] } ], "source": [ "# 1. Determine which columns contain probe IDs and gene symbols\n", "# From the preview, we can see:\n", "# - 'ID' column contains probe IDs like \"1007_s_at\" which match the gene identifiers in the expression data\n", "# - 'Gene Symbol' column contains human gene symbols like \"DDR1 /// MIR4640\"\n", "\n", "# 2. Get gene mapping dataframe by extracting the ID and Gene Symbol columns\n", "mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Gene Symbol')\n", "\n", "# Preview the mapping data\n", "print(\"Gene mapping preview:\")\n", "print(preview_df(mapping_df))\n", "\n", "# 3. Apply the gene mapping to convert probe-level measurements to gene expression data\n", "gene_data = apply_gene_mapping(gene_data, mapping_df)\n", "\n", "# Preview the resulting gene expression data\n", "print(\"\\nGene expression data preview (after mapping):\")\n", "print(f\"Number of genes: {len(gene_data)}\")\n", "print(f\"Number of samples: {gene_data.shape[1]}\")\n", "print(preview_df(gene_data))\n", "\n", "# Save the processed gene 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\"\\nGene expression data saved to {out_gene_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "07d63559", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "8e90a400", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:39:25.259790Z", "iopub.status.busy": "2025-03-25T08:39:25.259669Z", "iopub.status.idle": "2025-03-25T08:39:26.041936Z", "shell.execute_reply": "2025-03-25T08:39:26.041571Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data shape: (19845, 68)\n", "First few genes with their expression values after normalization:\n", " GSM343029 GSM343030 GSM343031 GSM343032 GSM343033 GSM343034 \\\n", "Gene \n", "A1BG 125.24 109.31 113.71 107.14 102.77 100.74 \n", "A1BG-AS1 115.75 168.38 174.90 124.05 151.74 150.76 \n", "A1CF 93.98 134.31 119.44 105.67 117.64 111.80 \n", "A2M 2135.54 1467.21 1383.66 1574.30 1700.99 1631.14 \n", "A2M-AS1 156.68 67.45 93.90 140.36 86.04 146.31 \n", "\n", " GSM343035 GSM343036 GSM343037 GSM343038 ... GSM343087 \\\n", "Gene ... \n", "A1BG 99.52 110.14 119.63 113.36 ... 104.37 \n", "A1BG-AS1 140.66 186.51 141.71 160.39 ... 144.49 \n", "A1CF 105.67 114.62 149.63 153.93 ... 110.87 \n", "A2M 1924.62 1101.58 1820.77 1790.31 ... 1937.06 \n", "A2M-AS1 166.86 77.69 140.92 116.04 ... 110.65 \n", "\n", " GSM343088 GSM343089 GSM343090 GSM343091 GSM343092 GSM343093 \\\n", "Gene \n", "A1BG 95.92 113.77 110.98 120.70 115.13 118.34 \n", "A1BG-AS1 117.62 133.32 146.37 120.06 171.98 147.19 \n", "A1CF 90.58 82.22 115.93 81.67 104.60 111.89 \n", "A2M 2895.52 3777.80 3264.79 2687.43 974.38 2940.72 \n", "A2M-AS1 193.40 144.23 191.21 185.32 78.36 155.90 \n", "\n", " GSM343094 GSM343095 GSM343096 \n", "Gene \n", "A1BG 103.11 103.51 103.10 \n", "A1BG-AS1 134.13 131.04 176.26 \n", "A1CF 122.13 106.91 136.77 \n", "A2M 1441.71 1965.61 2336.76 \n", "A2M-AS1 87.10 104.06 104.50 \n", "\n", "[5 rows x 68 columns]\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data saved to ../../output/preprocess/Duchenne_Muscular_Dystrophy/gene_data/GSE13608.csv\n", "Loaded clinical features from ../../output/preprocess/Duchenne_Muscular_Dystrophy/clinical_data/GSE13608.csv\n", "Clinical features shape: (3, 30)\n", "Linked data shape: (98, 19848)\n", "Linked data preview (first 5 rows, first 5 columns):\n", " 0 1 2 A1BG A1BG-AS1\n", "0 0.0 NaN 0.0 NaN NaN\n", "1 0.0 55.0 1.0 NaN NaN\n", "2 0.0 54.0 NaN NaN NaN\n", "3 0.0 25.0 NaN NaN NaN\n", "4 0.0 29.0 NaN NaN NaN\n", "Missing values before handling:\n", "Error processing data: '0'\n", "Abnormality detected in the cohort: GSE13608. Preprocessing failed.\n", "Data was determined to be unusable and was not saved\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", "# 2. Load the clinical data from the previously saved file\n", "try:\n", " # Load the previously saved clinical data\n", " clinical_features = pd.read_csv(out_clinical_data_file)\n", " print(f\"Loaded clinical features from {out_clinical_data_file}\")\n", " print(f\"Clinical features shape: {clinical_features.shape}\")\n", " \n", " # Determine the actual column names in the clinical features dataframe\n", " trait_column = \"0\" # Based on previous step output\n", " age_column = \"1\" if \"1\" in clinical_features.columns else None\n", " gender_column = \"2\" if \"2\" in clinical_features.columns else None\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", " if not linked_data.empty:\n", " print(linked_data.iloc[:5, :5])\n", " \n", " # 4. Handle missing values\n", " print(\"Missing values before handling:\")\n", " print(f\" Trait (column {trait_column}) missing: {linked_data[trait_column].isna().sum()} out of {len(linked_data)}\")\n", " if age_column and age_column in linked_data.columns:\n", " print(f\" Age (column {age_column}) missing: {linked_data[age_column].isna().sum()} out of {len(linked_data)}\")\n", " if gender_column and gender_column in linked_data.columns:\n", " print(f\" Gender (column {gender_column}) missing: {linked_data[gender_column].isna().sum()} out of {len(linked_data)}\")\n", " \n", " gene_cols = [col for col in linked_data.columns if col not in [trait_column, age_column, gender_column]]\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_column)\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_column)\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 non-DMD samples.\"\n", " )\n", " \n", " # 7. Save if usable\n", " if is_usable and len(cleaned_data) > 0:\n", " # Rename columns to more descriptive names before saving\n", " column_mapping = {}\n", " if trait_column in cleaned_data.columns:\n", " column_mapping[trait_column] = trait\n", " if age_column in cleaned_data.columns:\n", " column_mapping[age_column] = \"Age\"\n", " if gender_column in cleaned_data.columns:\n", " column_mapping[gender_column] = \"Gender\"\n", " \n", " if column_mapping:\n", " cleaned_data = cleaned_data.rename(columns=column_mapping)\n", " \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 }