{ "cells": [ { "cell_type": "markdown", "id": "2f04eee0-5928-4e74-a754-6dc2e528810c", "metadata": {}, "source": [ "# EnsembleAgeStaticTop" ] }, { "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)" ] }, { "cell_type": "markdown", "id": "d95fafdc-643a-40ea-a689-200bd132e90c", "metadata": {}, "source": [ "Let's first import some packages:" ] }, { "cell_type": "code", "execution_count": 16, "id": "4adfb4de-cd79-4913-a1af-9e23e9e236c9", "metadata": { "execution": { "iopub.execute_input": "2024-03-05T20:16:52.672190Z", "iopub.status.busy": "2024-03-05T20:16:52.671672Z", "iopub.status.idle": "2024-03-05T20:16:53.985159Z", "shell.execute_reply": "2024-03-05T20:16:53.984861Z" } }, "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": 17, "id": "8aa77372-7ed3-4da7-abc9-d30372106139", "metadata": { "execution": { "iopub.execute_input": "2024-03-05T20:16:53.987198Z", "iopub.status.busy": "2024-03-05T20:16:53.987026Z", "iopub.status.idle": "2024-03-05T20:16:53.993902Z", "shell.execute_reply": "2024-03-05T20:16:53.993654Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "class EnsembleAgeStaticTop(pyagingModel):\n", " def __init__(self):\n", " super().__init__()\n", "\n", " def preprocess(self, x):\n", " return x\n", "\n", " def postprocess(self, x):\n", " return x\n", "\n" ] } ], "source": [ "def print_entire_class(cls):\n", " source = inspect.getsource(cls)\n", " print(source)\n", "\n", "print_entire_class(pya.models.EnsembleAgeStaticTop)" ] }, { "cell_type": "code", "execution_count": 18, "id": "78536494-f1d9-44de-8583-c89a310d2307", "metadata": { "execution": { "iopub.execute_input": "2024-03-05T20:16:53.995398Z", "iopub.status.busy": "2024-03-05T20:16:53.995310Z", "iopub.status.idle": "2024-03-05T20:16:53.996887Z", "shell.execute_reply": "2024-03-05T20:16:53.996634Z" } }, "outputs": [], "source": [ "model = pya.models.EnsembleAgeStaticTop()" ] }, { "cell_type": "markdown", "id": "51f8615e-01fa-4aa5-b196-3ee2b35d261c", "metadata": {}, "source": [ "## Define clock metadata" ] }, { "cell_type": "code", "execution_count": 19, "id": "6601da9e-8adc-44ee-9308-75e3cd31b816", "metadata": { "execution": { "iopub.execute_input": "2024-03-05T20:16:53.998322Z", "iopub.status.busy": "2024-03-05T20:16:53.998245Z", "iopub.status.idle": "2024-03-05T20:16:54.000117Z", "shell.execute_reply": "2024-03-05T20:16:53.999888Z" } }, "outputs": [], "source": [ "model.metadata[\"clock_name\"] = \"ensembleagestatictop\"\n", "model.metadata[\"data_type\"] = \"DNA methylation\" # Paper: EnsembleAge integrates predictions from multiple penalized models.\n", "model.metadata[\"species\"] = \"Mus musculus\" # Paper: EnsembleAge integrates predictions from multiple penalized models.\n", "model.metadata[\"year\"] = 2025\n", "model.metadata[\"approved_by_author\"] = \"⌛\"\n", "model.metadata[\"citation\"] = \"Haghani, A. et al. EnsembleAge: enhancing epigenetic age assessment with a multi-clock framework. GeroScience 48, 2873-2886 (2025).\"\n", "model.metadata[\"doi\"] = \"https://doi.org/10.1007/s11357-025-01808-1\"\n", "model.metadata[\"notes\"] = \"Static.Top is a single elastic-net predictor of the calibrated age from the most intervention-responsive constituent clock, trained on perturbed MethylGauge mice.\"\n", "model.metadata[\"research_only\"] = None\n", "model.metadata[\"tissue\"] = [\"multi-tissue\"] # Paper: Clock training used liver, blood, brain, and other mouse tissues.\n", "model.metadata[\"predicts\"] = [\"intervention-responsive epigenetic age\"] # Paper: EnsembleAge integrates predictions from multiple penalized models.\n", "model.metadata[\"training_target\"] = [\"intervention-responsive epigenetic age\"] # Paper: The second static type was optimized for the most responsive clock.\n", "model.metadata[\"unit\"] = [\"years\"] # Paper: EnsembleAge.Static.Top_ElasticNoAgeTraf\n", "model.metadata[\"model_type\"] = \"elastic net regression\" # Paper: The clocks were trained using ridge, lasso, and elastic net regression.\n", "model.metadata[\"platform\"] = [\"Horvath MammalMethylChip40\", \"Horvath MammalMethylChip320\"] # Paper: Data were generated using Mammal40k or Mammal320k BeadChip platforms.\n", "model.metadata[\"population\"] = \"mice\" # Paper: Static models were trained exclusively on treated or perturbed animals.\n", "model.metadata[\"journal\"] = \"GeroScience\"\n", "model.metadata[\"last_author\"] = \"Steve Horvath\"\n", "model.metadata[\"n_features\"] = 431\n", "model.metadata[\"citations\"] = 3\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": "3a134f95-062f-4f6f-ad5c-a088f07d4ecc", "metadata": {}, "source": [ "#### Download directly with curl" ] }, { "cell_type": "code", "execution_count": 20, "id": "40edcd18-89a0-4d98-ab1e-4a12e6c6017a", "metadata": { "execution": { "iopub.execute_input": "2024-03-05T20:16:54.001576Z", "iopub.status.busy": "2024-03-05T20:16:54.001503Z", "iopub.status.idle": "2024-03-05T20:16:54.464541Z", "shell.execute_reply": "2024-03-05T20:16:54.463458Z" } }, "outputs": [ { "data": { "text/plain": [ "0" ] }, "execution_count": 20, "metadata": {}, "output_type": "execute_result" } ], "source": [ "supplementary_url = \"https://static-content.springer.com/esm/art%3A10.1007%2Fs11357-025-01808-1/MediaObjects/11357_2025_1808_MOESM1_ESM.xlsx\"\n", "supplementary_file_name = \"coefficients.xlsx\"\n", "os.system(f\"curl -o {supplementary_file_name} {supplementary_url}\")" ] }, { "cell_type": "markdown", "id": "5035b180-3d1b-4432-8ebe-b9c92bd93a7f", "metadata": {}, "source": [ "## Load features" ] }, { "cell_type": "markdown", "id": "793d7b24-b1ef-4dd2-ac26-079f7b67fba7", "metadata": {}, "source": [ "#### From Excel file" ] }, { "cell_type": "code", "execution_count": 21, "id": "110a5ded-d25f-4cef-8e84-4f51210dfc26", "metadata": { "execution": { "iopub.execute_input": "2024-03-05T20:16:54.470022Z", "iopub.status.busy": "2024-03-05T20:16:54.469736Z", "iopub.status.idle": "2024-03-05T20:16:54.620659Z", "shell.execute_reply": "2024-03-05T20:16:54.620381Z" } }, "outputs": [], "source": [ "df = pd.read_excel('coefficients.xlsx', sheet_name='Table S3. Ensemble.Static')\n", "df = df[df['EnsembleAge.Static.Top_ElasticNoAgeTraf'] != 0]\n", "model.features = df['CGid'][1:].tolist()" ] }, { "cell_type": "markdown", "id": "ee6d8fa0-4767-4c45-9717-eb1c95e2ddc0", "metadata": {}, "source": [ "## Load weights into base model" ] }, { "cell_type": "code", "execution_count": 22, "id": "e09b3463-4fd4-41b1-ac21-e63ddd223fe0", "metadata": { "execution": { "iopub.execute_input": "2024-03-05T20:16:54.622343Z", "iopub.status.busy": "2024-03-05T20:16:54.622259Z", "iopub.status.idle": "2024-03-05T20:16:54.624293Z", "shell.execute_reply": "2024-03-05T20:16:54.624024Z" } }, "outputs": [], "source": [ "weights = torch.tensor(df['EnsembleAge.Static.Top_ElasticNoAgeTraf'][1:].tolist()).unsqueeze(0).float()\n", "intercept = torch.tensor([df['EnsembleAge.Static.Top_ElasticNoAgeTraf'][0]]).float()" ] }, { "cell_type": "markdown", "id": "ad261636-5b00-4979-bb1d-67a851f7aa19", "metadata": {}, "source": [ "#### Linear model" ] }, { "cell_type": "code", "execution_count": 23, "id": "d7f43b99-26f2-4622-9a76-316712058877", "metadata": { "execution": { "iopub.execute_input": "2024-03-05T20:16:54.625773Z", "iopub.status.busy": "2024-03-05T20:16:54.625694Z", "iopub.status.idle": "2024-03-05T20:16:54.627580Z", "shell.execute_reply": "2024-03-05T20:16:54.627360Z" } }, "outputs": [], "source": [ "base_model = pya.models.LinearModel(input_dim=len(model.features))\n", "\n", "base_model.linear.weight.data = weights.float()\n", "base_model.linear.bias.data = intercept.float()\n", "\n", "model.base_model = base_model" ] }, { "cell_type": "markdown", "id": "ad8b4c1d-9d57-48b7-9a30-bcfea7b747b1", "metadata": {}, "source": [ "## Load reference values" ] }, { "cell_type": "code", "execution_count": 24, "id": "ade0f4c9-2298-4fc3-bb72-d200907dd731", "metadata": { "execution": { "iopub.execute_input": "2024-03-05T20:16:54.628921Z", "iopub.status.busy": "2024-03-05T20:16:54.628842Z", "iopub.status.idle": "2024-03-05T20:16:54.630287Z", "shell.execute_reply": "2024-03-05T20:16:54.630036Z" } }, "outputs": [], "source": [ "model.reference_values = None" ] }, { "cell_type": "markdown", "id": "af3bcf7b-74a8-4d21-9ccb-4de0c2b0516b", "metadata": {}, "source": [ "## Load preprocess and postprocess objects" ] }, { "cell_type": "code", "execution_count": 25, "id": "7a22fb20-c605-424d-8efb-7620c2c0755c", "metadata": { "execution": { "iopub.execute_input": "2024-03-05T20:16:54.631740Z", "iopub.status.busy": "2024-03-05T20:16:54.631663Z", "iopub.status.idle": "2024-03-05T20:16:54.633075Z", "shell.execute_reply": "2024-03-05T20:16:54.632860Z" } }, "outputs": [], "source": [ "model.preprocess_name = None\n", "model.preprocess_dependencies = None" ] }, { "cell_type": "code", "execution_count": 26, "id": "ff4a21cb-cf41-44dc-9ed1-95cf8aa15772", "metadata": { "execution": { "iopub.execute_input": "2024-03-05T20:16:54.634482Z", "iopub.status.busy": "2024-03-05T20:16:54.634376Z", "iopub.status.idle": "2024-03-05T20:16:54.635863Z", "shell.execute_reply": "2024-03-05T20:16:54.635655Z" } }, "outputs": [], "source": [ "model.postprocess_name = None\n", "model.postprocess_dependencies = None" ] }, { "cell_type": "markdown", "id": "86e3d6b1-e67e-4f3d-bd39-0ebec5726c3c", "metadata": {}, "source": [ "## Check all clock parameters" ] }, { "cell_type": "code", "execution_count": 27, "id": "2168355c-47d9-475d-b816-49f65e74887c", "metadata": { "execution": { "iopub.execute_input": "2024-03-05T20:16:54.637289Z", "iopub.status.busy": "2024-03-05T20:16:54.637208Z", "iopub.status.idle": "2024-03-05T20:16:54.640087Z", "shell.execute_reply": "2024-03-05T20:16:54.639876Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "%==================================== Model Details ====================================%\n", "Model Attributes:\n", "\n", "training: True\n", "metadata: {'approved_by_author': '⌛',\n", " 'citation': 'Haghani, A., Lu, A.T., Yan, Q. et al. EnsembleAge: enhancing '\n", " 'epigenetic age assessment with a multi-clock framework. '\n", " 'GeroScience (2025)',\n", " 'clock_name': 'ensembleagestatictop',\n", " 'data_type': 'methylation',\n", " 'doi': 'https://doi.org/10.1007/s11357-025-01808-1',\n", " 'notes': None,\n", " 'research_only': None,\n", " 'species': 'Mus musculus',\n", " 'version': None,\n", " 'year': 2025}\n", "reference_values: None\n", "preprocess_name: None\n", "preprocess_dependencies: None\n", "postprocess_name: None\n", "postprocess_dependencies: None\n", "features: ['cg00045149', 'cg00091964', 'cg00117955', 'cg00158333', 'cg00181698', 'cg00243488', 'cg00258262', 'cg00259292', 'cg00407148', 'cg00409684', 'cg00493887', 'cg00553880', 'cg00578937', 'cg00659065', 'cg00896209', 'cg00929113', 'cg00946032', 'cg00957561', 'cg01024113', 'cg01039540', 'cg01061575', 'cg01099625', 'cg01134518', 'cg01149078', 'cg01294450', 'cg01473155', 'cg01486146', 'cg01553138', 'cg01621100', 'cg01657263']... [Total elements: 431]\n", "base_model_features: None\n", "\n", "%==================================== Model Details ====================================%\n", "Model Structure:\n", "\n", "base_model: LinearModel(\n", " (linear): Linear(in_features=431, out_features=1, bias=True)\n", ")\n", "\n", "%==================================== Model Details ====================================%\n", "Model Parameters and Weights:\n", "\n", "base_model.linear.weight: [0.1743975728750229, -0.04364413395524025, 0.22944891452789307, 0.2686740756034851, 0.01912594959139824, -0.09232170134782791, 0.11978655308485031, -0.0801130011677742, 0.5056779384613037, 0.1736055165529251, -0.473909854888916, -0.20611447095870972, 1.324728012084961, -0.05422835797071457, -0.2410501092672348, -0.42427003383636475, -0.39920952916145325, -0.20043838024139404, -0.008536707609891891, -0.09825412929058075, 0.16520655155181885, 0.012782384641468525, 0.01064230501651764, -0.1301790326833725, -0.6252124309539795, -0.0008419872610829771, 0.10042154788970947, -0.013664733618497849, 0.16023848950862885, 0.023345399647951126]... [Tensor of shape torch.Size([1, 431])]\n", "base_model.linear.bias: tensor([5.7927])\n", "\n", "%==================================== Model Details ====================================%\n", "\n" ] } ], "source": [ "pya.utils.print_model_details(model)" ] }, { "cell_type": "markdown", "id": "986d0262-e0c7-4036-b687-dee53ba392fb", "metadata": {}, "source": [ "## Basic test" ] }, { "cell_type": "code", "execution_count": 28, "id": "936b9877-d076-4ced-99aa-e8d4c58c5caf", "metadata": { "execution": { "iopub.execute_input": "2024-03-05T20:16:54.641688Z", "iopub.status.busy": "2024-03-05T20:16:54.641533Z", "iopub.status.idle": "2024-03-05T20:16:54.644751Z", "shell.execute_reply": "2024-03-05T20:16:54.644511Z" } }, "outputs": [ { "data": { "text/plain": [ "tensor([[ -9.4919],\n", " [ -4.8999],\n", " [-11.6078],\n", " [ 5.9647],\n", " [ 23.9748],\n", " [ 3.0499],\n", " [-12.5388],\n", " [ 4.6096],\n", " [ 5.1646],\n", " [-10.7823]], dtype=torch.float64, grad_fn=)" ] }, "execution_count": 28, "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" ] }, { "cell_type": "code", "execution_count": 29, "id": "5ef2fa8d-c80b-4fdd-8555-79c0d541788e", "metadata": { "execution": { "iopub.execute_input": "2024-03-05T20:16:54.646217Z", "iopub.status.busy": "2024-03-05T20:16:54.646142Z", "iopub.status.idle": "2024-03-05T20:16:54.648738Z", "shell.execute_reply": "2024-03-05T20:16:54.648503Z" } }, "outputs": [], "source": [ "torch.save(model, f\"../weights/{model.metadata['clock_name']}.pt\")" ] }, { "cell_type": "markdown", "id": "bac6257b-8d08-4a90-8d0b-7f745dc11ac1", "metadata": {}, "source": [ "## Clear directory\n", "" ] }, { "cell_type": "code", "execution_count": 30, "id": "11aeaa70-44c0-42f9-86d7-740e3849a7a6", "metadata": { "execution": { "iopub.execute_input": "2024-03-05T20:16:54.650224Z", "iopub.status.busy": "2024-03-05T20:16:54.650146Z", "iopub.status.idle": "2024-03-05T20:16:54.653052Z", "shell.execute_reply": "2024-03-05T20:16:54.652811Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Deleted file: coefficients.xlsx\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 }