{ "cells": [ { "cell_type": "markdown", "id": "2f04eee0-5928-4e74-a754-6dc2e528810c", "metadata": {}, "source": [ "# TwelveCellDeconvoluteBloodEPIC" ] }, { "cell_type": "markdown", "id": "a3f514a3-772c-4a14-afdf-5a8376851ff4", "metadata": {}, "source": [ "## Index\n", "1. [Instantiate model class](#Instantiate-model-class)\n", "2. [Define clock metadata](#Define-clock-metadata)\n", "3. [Download clock dependencies](#Download-clock-dependencies)\n", "5. [Load features](#Load-features)\n", "6. [Load weights into base model](#Load-weights-into-base-model)\n", "7. [Load reference values](#Load-reference-values)\n", "8. [Load preprocess and postprocess objects](#Load-preprocess-and-postprocess-objects)\n", "10. [Check all clock parameters](#Check-all-clock-parameters)\n", "10. [Basic test](#Basic-test)\n", "11. [Save torch model](#Save-torch-model)\n", "12. [Clear directory](#Clear-directory)\n" ] }, { "cell_type": "markdown", "id": "d95fafdc-643a-40ea-a689-200bd132e90c", "metadata": {}, "source": [ "Let's first import some packages:" ] }, { "cell_type": "code", "execution_count": 1, "id": "4adfb4de-cd79-4913-a1af-9e23e9e236c9", "metadata": { "execution": { "iopub.execute_input": "2025-04-07T17:47:34.133350Z", "iopub.status.busy": "2025-04-07T17:47:34.132902Z", "iopub.status.idle": "2025-04-07T17:47:35.476506Z", "shell.execute_reply": "2025-04-07T17:47:35.476150Z" } }, "outputs": [], "source": [ "import os\n", "import inspect\n", "import shutil\n", "import json\n", "import torch\n", "import pandas as pd\n", "import pyaging as pya" ] }, { "cell_type": "markdown", "id": "145082e5-ced4-47ae-88c0-cb69773e3c5a", "metadata": {}, "source": [ "## Instantiate model class" ] }, { "cell_type": "code", "execution_count": 2, "id": "8aa77372-7ed3-4da7-abc9-d30372106139", "metadata": { "execution": { "iopub.execute_input": "2025-04-07T17:47:35.478214Z", "iopub.status.busy": "2025-04-07T17:47:35.477997Z", "iopub.status.idle": "2025-04-07T17:47:35.484695Z", "shell.execute_reply": "2025-04-07T17:47:35.484415Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "class TwelveCellDeconvoluteBloodEPIC(DeconvolutionSingleCell):\n", " def __init__(self):\n", " super().__init__()\n", "\n" ] } ], "source": [ "def print_entire_class(cls):\n", " source = inspect.getsource(cls)\n", " print(source)\n", "\n", "print_entire_class(pya.models.TwelveCellDeconvoluteBloodEPIC)\n" ] }, { "cell_type": "code", "execution_count": 3, "id": "78536494-f1d9-44de-8583-c89a310d2307", "metadata": { "execution": { "iopub.execute_input": "2025-04-07T17:47:35.485963Z", "iopub.status.busy": "2025-04-07T17:47:35.485866Z", "iopub.status.idle": "2025-04-07T17:47:35.487577Z", "shell.execute_reply": "2025-04-07T17:47:35.487295Z" } }, "outputs": [], "source": [ "model = pya.models.TwelveCellDeconvoluteBloodEPIC()" ] }, { "cell_type": "markdown", "id": "51f8615e-01fa-4aa5-b196-3ee2b35d261c", "metadata": {}, "source": [ "## Define clock metadata" ] }, { "cell_type": "code", "execution_count": 4, "id": "6601da9e-8adc-44ee-9308-75e3cd31b816", "metadata": { "execution": { "iopub.execute_input": "2025-04-07T17:47:35.488812Z", "iopub.status.busy": "2025-04-07T17:47:35.488727Z", "iopub.status.idle": "2025-04-07T17:47:35.490718Z", "shell.execute_reply": "2025-04-07T17:47:35.490459Z" } }, "outputs": [], "source": [ "model.metadata[\"clock_name\"] = \"twelvecelldeconvolutebloodepicneu\"\n", "model.metadata[\"data_type\"] = \"DNA methylation\" # Paper: The TwelveCell model is a DeconvolutionModel whose reference rows are CpG loci.\n", "model.metadata[\"species\"] = \"Homo sapiens\" # Paper: The registry declares species Human for TwelveCellDeconvoluteBloodEPIC.\n", "model.metadata[\"year\"] = 2022\n", "model.metadata[\"approved_by_author\"] = \"⌛\"\n", "model.metadata[\"citation\"] = \"Salas, L.A., Zhang, Z., Koestler, D.C. et al. Enhanced cell deconvolution of peripheral blood using DNA methylation for high-resolution immune profiling. Nature Communications 13, 761 (2022).\"\n", "model.metadata[\"doi\"] = \"https://doi.org/10.1038/s41467-021-27864-7\"\n", "model.metadata[\"notes\"] = \"Reference-based constrained deconvolution returning the neutrophil proportion from EPIC-array blood methylation. The published EPIC IDOL-Ext library used 1,200 CpGs selected to optimize recovery of known artificial-mixture cell-type proportions; pyaging instead inherits Biolearn’s undocumented 240-CpG replacement, whose rows reproducibly comprise 10 positive and 10 negative maximal cell-versus-other methylation contrasts per subtype and are not a subset of the published 1,200 probes.\"\n", "model.metadata[\"research_only\"] = None\n", "model.metadata[\"tissue\"] = [\"purified blood leukocytes\"] # Paper: The reference-matrix columns are twelve leukocyte subtypes used to deconvolve peripheral blood.\n", "model.metadata[\"predicts\"] = [\"neutrophil proportion\"] # Paper: The model output is Cell Proportions and Neu is one of the twelve returned columns.\n", "model.metadata[\"training_target\"] = [\"cell-type proportions\"] # Paper: IDOL used artificial-mixture ground truth with known, prespecified proportions of the 12 cell types and optimized libraries by comparing deconvolution estimates with those known proportions.\n", "model.metadata[\"unit\"] = [\"proportion\"] # Paper: The solver constrains each estimated cell proportion to 0–1 and all proportions to sum to one.\n", "model.metadata[\"model_type\"] = \"reference-based constrained deconvolution\" # Paper: The implementation minimizes reference-matrix reconstruction error by constrained quadratic programming.\n", "model.metadata[\"platform\"] = [\"Illumina EPIC\"] # Paper: The TwelveCell model registry sets platform to EPIC.\n", "model.metadata[\"population\"] = \"adults\" # Paper: Reference cells were isolated from 41 male and 15 female anonymous healthy donors with mean age 32.2 years and range 19–58 years, spanning multiple self-identified ancestries.\n", "model.metadata[\"journal\"] = \"Nature Communications\"\n", "model.metadata[\"last_author\"] = \"Brock C. Christensen\"\n", "model.metadata[\"n_features\"] = 240\n", "model.metadata[\"citations\"] = 13\n", "model.metadata[\"citations_date\"] = \"2026-07-05\"\n" ] }, { "cell_type": "markdown", "id": "74492239-5aae-4026-9d90-6bc9c574c110", "metadata": {}, "source": [ "## Download clock dependencies" ] }, { "cell_type": "markdown", "id": "7bec474f-80ce-4884-9472-30c193327117", "metadata": {}, "source": [ "#### Download reference file" ] }, { "cell_type": "code", "execution_count": 5, "id": "aa4a1b59-dda3-4ea8-8f34-b3c53ecbc310", "metadata": { "execution": { "iopub.execute_input": "2025-04-07T17:47:35.492080Z", "iopub.status.busy": "2025-04-07T17:47:35.491992Z", "iopub.status.idle": "2025-04-07T17:47:36.204837Z", "shell.execute_reply": "2025-04-07T17:47:36.204380Z" } }, "outputs": [ { "data": { "text/plain": [ "0" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "coeff_url = \"https://raw.githubusercontent.com/bio-learn/biolearn/master/biolearn/data/twelve_cell_deconv.csv\"\n", "os.system(f\"curl -L {coeff_url} -o twelve_cell_deconv.csv\")\n" ] }, { "cell_type": "markdown", "id": "5035b180-3d1b-4432-8ebe-b9c92bd93a7f", "metadata": {}, "source": [ "## Load features" ] }, { "cell_type": "markdown", "id": "15f4af76-b93c-438c-b57f-f129d6e9ec99", "metadata": {}, "source": [ "#### From CSV file" ] }, { "cell_type": "code", "execution_count": 6, "id": "f26a49e3-7389-416c-9080-539f50e9abd0", "metadata": { "execution": { "iopub.execute_input": "2025-04-07T17:47:36.206985Z", "iopub.status.busy": "2025-04-07T17:47:36.206832Z", "iopub.status.idle": "2025-04-07T17:47:36.211174Z", "shell.execute_reply": "2025-04-07T17:47:36.210783Z" } }, "outputs": [], "source": [ "import numpy as np\n", "import pandas as pd\n", "\n", "ref = pd.read_csv('twelve_cell_deconv.csv', index_col=0)\n", "model.features = ref.index.astype(str).tolist()\n", "\n", "ref_matrix = torch.tensor(ref.values, dtype=torch.float64)\n", "pseudo_inv = torch.linalg.pinv(ref_matrix)\n", "\n", "model.pseudo_inv = pseudo_inv\n", "model.cell_index = 10\n", "model.reference_values = torch.nanmean(ref_matrix, dim=1)\n" ] }, { "cell_type": "markdown", "id": "ee6d8fa0-4767-4c45-9717-eb1c95e2ddc0", "metadata": {}, "source": [ "## Load weights into base model" ] }, { "cell_type": "markdown", "id": "d79e5690-e284-4de6-8460-d3545a8192af", "metadata": {}, "source": [ "#### From CSV file" ] }, { "cell_type": "code", "execution_count": 7, "id": "7f6187ed-fcff-4ff2-bcb1-b5bcef8190e8", "metadata": { "execution": { "iopub.execute_input": "2025-04-07T17:47:36.213121Z", "iopub.status.busy": "2025-04-07T17:47:36.212960Z", "iopub.status.idle": "2025-04-07T17:47:36.216800Z", "shell.execute_reply": "2025-04-07T17:47:36.216396Z" } }, "outputs": [], "source": [ "# No linear base model; deconvolution logic in model forward\n" ] }, { "cell_type": "markdown", "id": "ad261636-5b00-4979-bb1d-67a851f7aa19", "metadata": {}, "source": [ "#### Linear model" ] }, { "cell_type": "code", "execution_count": 8, "id": "d7f43b99-26f2-4622-9a76-316712058877", "metadata": { "execution": { "iopub.execute_input": "2025-04-07T17:47:36.218646Z", "iopub.status.busy": "2025-04-07T17:47:36.218507Z", "iopub.status.idle": "2025-04-07T17:47:36.221310Z", "shell.execute_reply": "2025-04-07T17:47:36.220958Z" } }, "outputs": [], "source": [ "model.base_model = None\n" ] }, { "cell_type": "markdown", "id": "ad8b4c1d-9d57-48b7-9a30-bcfea7b747b1", "metadata": {}, "source": [ "## Load reference values" ] }, { "cell_type": "code", "execution_count": 9, "id": "90d45266-962d-41b6-927c-6a147ed41305", "metadata": { "execution": { "iopub.execute_input": "2025-04-07T17:47:36.222862Z", "iopub.status.busy": "2025-04-07T17:47:36.222749Z", "iopub.status.idle": "2025-04-07T17:47:36.224649Z", "shell.execute_reply": "2025-04-07T17:47:36.224309Z" } }, "outputs": [], "source": [ "# reference_values already set above" ] }, { "cell_type": "markdown", "id": "af3bcf7b-74a8-4d21-9ccb-4de0c2b0516b", "metadata": {}, "source": [ "## Load preprocess and postprocess objects" ] }, { "cell_type": "code", "execution_count": 10, "id": "f7d32b69-e20e-42ff-aba9-d07b9b44dbd1", "metadata": { "execution": { "iopub.execute_input": "2025-04-07T17:47:36.226270Z", "iopub.status.busy": "2025-04-07T17:47:36.226156Z", "iopub.status.idle": "2025-04-07T17:47:36.228064Z", "shell.execute_reply": "2025-04-07T17:47:36.227750Z" } }, "outputs": [], "source": [ "model.preprocess_name = \"fill_with_reference_means\"\n", "model.preprocess_dependencies = None\n" ] }, { "cell_type": "code", "execution_count": 11, "id": "7a22fb20-c605-424d-8efb-7620c2c0755c", "metadata": { "execution": { "iopub.execute_input": "2025-04-07T17:47:36.229604Z", "iopub.status.busy": "2025-04-07T17:47:36.229468Z", "iopub.status.idle": "2025-04-07T17:47:36.231233Z", "shell.execute_reply": "2025-04-07T17:47:36.230916Z" } }, "outputs": [], "source": [ "model.postprocess_name = None\n", "model.postprocess_dependencies = None\n" ] }, { "cell_type": "markdown", "id": "86e3d6b1-e67e-4f3d-bd39-0ebec5726c3c", "metadata": {}, "source": [ "## Check all clock parameters" ] }, { "cell_type": "code", "execution_count": 12, "id": "2168355c-47d9-475d-b816-49f65e74887c", "metadata": { "execution": { "iopub.execute_input": "2025-04-07T17:47:36.232808Z", "iopub.status.busy": "2025-04-07T17:47:36.232688Z", "iopub.status.idle": "2025-04-07T17:47:36.236913Z", "shell.execute_reply": "2025-04-07T17:47:36.236596Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "%==================================== Model Details ====================================%\n", "Model Attributes:\n", "\n", "training: True\n", "metadata: {'approved_by_author': '⌛',\n", " 'citation': 'Ying, Kejun, et al. \"A unified framework for systematic curation '\n", " 'and evaluation of aging biomarkers.\" Nature Aging (2025): 1-17.',\n", " 'clock_name': 'twelvecelldeconvolutebloodepicneu',\n", " 'data_type': 'methylation',\n", " 'doi': 'https://doi.org/10.1038/s43587-025-00987-y',\n", " 'notes': 'Estimated proportion of Neu from 12-cell EPIC reference.',\n", " 'research_only': None,\n", " 'species': 'Homo sapiens',\n", " 'version': None,\n", " 'year': 2024}\n", "reference_values: [0.9106685833333333, 0.8335768333333333, 0.8720161666666666, 0.8286470833333333, 0.92628525, 0.9155413333333334, 0.8792788333333332, 0.9127326666666665, 0.9067565833333332, 0.84800775, 0.10073516666666667, 0.14440299999999998, 0.049399916666666675, 0.08766050000000002, 0.07896441666666666, 0.12878258333333334, 0.16374524999999998, 0.13815541666666667, 0.17540216666666666, 0.1698345, 0.9202164166666665, 0.8607305833333334, 0.9136148333333334, 0.9245049999999999, 0.8901303333333334, 0.9271245, 0.8883705833333333, 0.8855881666666668, 0.9244469166666666, 0.92171125]... [Tensor of shape torch.Size([240])]\n", "preprocess_name: 'fill_with_reference_means'\n", "preprocess_dependencies: None\n", "postprocess_name: None\n", "postprocess_dependencies: None\n", "features: ['cg11778706', 'cg13745692', 'cg15163862', 'cg15667493', 'cg09590647', 'cg24160371', 'cg04200580', 'cg02177087', 'cg02690807', 'cg08486432', 'cg08674813', 'cg17565444', 'cg20208538', 'cg08747761', 'cg16576285', 'cg08269714', 'cg10931172', 'cg18421366', 'cg06805218', 'cg21268578', 'cg23635663', 'cg10712263', 'cg03984633', 'cg27576286', 'cg00789615', 'cg20591136', 'cg08012294', 'cg19811231', 'cg13335048', 'cg27109907']... [Total elements: 240]\n", "base_model_features: None\n", "base_model: None\n", "pseudo_inv: [0.0062597217235298664, 0.01539477951995796, 0.003836934604777173, 0.005564101437478809, 0.002277140363479023, 0.006073633184626901, 0.008477183290511526, -0.0001975656527457585, 0.005601139656499912, 0.007094362071883866, -0.006240708820602573, -0.009260375574434002, -0.0010103501546960773, -2.0931822748843616e-05, -0.003443105142629081, -0.006973754074381415, -0.014081560765767536, -0.01165024465832652, -0.017254358157385866, -0.018101141218108914, 0.016011891819700665, 0.007716146910953028, 0.01145146135203884, 0.007735843885753704, 0.014959580407076114, 0.011932867918461359, 0.014137094238940516, 0.016570818459337337, 0.006383014308174419, 0.007057464604785132]... [Tensor of shape torch.Size([12, 240])]\n", "cell_index: 10\n", "\n", "%==================================== Model Details ====================================%\n", "Model Structure:\n", "\n", "\n", "%==================================== Model Details ====================================%\n", "Model Parameters and Weights:\n", "\n", "\n", "%==================================== Model Details ====================================%\n", "\n" ] } ], "source": [ "pya.utils.print_model_details(model)" ] }, { "cell_type": "markdown", "id": "2f0a4df8", "metadata": {}, "source": [ "## Basic Test" ] }, { "cell_type": "code", "execution_count": 13, "id": "936b9877-d076-4ced-99aa-e8d4c58c5caf", "metadata": { "execution": { "iopub.execute_input": "2025-04-07T17:47:36.238465Z", "iopub.status.busy": "2025-04-07T17:47:36.238354Z", "iopub.status.idle": "2025-04-07T17:47:36.242868Z", "shell.execute_reply": "2025-04-07T17:47:36.242565Z" } }, "outputs": [ { "data": { "text/plain": [ "tensor([[0.0000],\n", " [0.0121],\n", " [0.0000],\n", " [0.0000],\n", " [0.0000],\n", " [0.0000],\n", " [0.2412],\n", " [0.1009],\n", " [0.2960],\n", " [0.0000]], dtype=torch.float64)" ] }, "execution_count": 13, "metadata": {}, "output_type": "execute_result" } ], "source": [ "torch.manual_seed(42)\n", "input = torch.randn(10, len(model.features), dtype=float)\n", "model.eval()\n", "model.to(float)\n", "pred = model(input)\n", "pred" ] }, { "cell_type": "markdown", "id": "fe8299d7-9285-4e22-82fd-b664434b4369", "metadata": {}, "source": [ "## Save torch model\n" ] }, { "cell_type": "code", "execution_count": 14, "id": "5ef2fa8d-c80b-4fdd-8555-79c0d541788e", "metadata": { "execution": { "iopub.execute_input": "2025-04-07T17:47:36.244263Z", "iopub.status.busy": "2025-04-07T17:47:36.244159Z", "iopub.status.idle": "2025-04-07T17:47:36.246682Z", "shell.execute_reply": "2025-04-07T17:47:36.246395Z" } }, "outputs": [], "source": [ "torch.save(model, f\"../weights/{model.metadata['clock_name']}.pt\")" ] }, { "cell_type": "markdown", "id": "bac6257b-8d08-4a90-8d0b-7f745dc11ac1", "metadata": {}, "source": [ "\n", "## Clear directory\n", "\n" ] }, { "cell_type": "code", "execution_count": 15, "id": "11aeaa70-44c0-42f9-86d7-740e3849a7a6", "metadata": { "execution": { "iopub.execute_input": "2025-04-07T17:47:36.248184Z", "iopub.status.busy": "2025-04-07T17:47:36.248077Z", "iopub.status.idle": "2025-04-07T17:47:36.255709Z", "shell.execute_reply": "2025-04-07T17:47:36.255449Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Deleted file: twelve_cell_deconv.csv\n" ] } ], "source": [ "# Function to remove a folder and all its contents\n", "def remove_folder(path):\n", " try:\n", " shutil.rmtree(path)\n", " print(f\"Deleted folder: {path}\")\n", " except Exception as e:\n", " print(f\"Error deleting folder {path}: {e}\")\n", "\n", "# Get a list of all files and folders in the current directory\n", "all_items = os.listdir('.')\n", "\n", "# Loop through the items\n", "for item in all_items:\n", " # Check if it's a file and does not end with .ipynb\n", " if os.path.isfile(item) and not item.endswith('.ipynb'):\n", " os.remove(item)\n", " print(f\"Deleted file: {item}\")\n", " # Check if it's a folder\n", " elif os.path.isdir(item):\n", " remove_folder(item)" ] } ], "metadata": { "kernelspec": { "display_name": "research", "language": "python", "name": "python3" }, "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.9.7" } }, "nbformat": 4, "nbformat_minor": 5 }