{ "cells": [ { "cell_type": "markdown", "id": "8d5655aa", "metadata": {}, "source": [ "# EnsembleAgeHumanMouse" ] }, { "cell_type": "markdown", "id": "abb20db3", "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": "94d11f61", "metadata": {}, "source": [ "Let's first import some packages:" ] }, { "cell_type": "code", "execution_count": 1, "id": "28ef9e62", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:34:33.693286Z", "iopub.status.busy": "2026-07-04T19:34:33.693156Z", "iopub.status.idle": "2026-07-04T19:34:35.684479Z", "shell.execute_reply": "2026-07-04T19:34:35.683969Z" } }, "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": "2755a48c", "metadata": {}, "source": [ "## Instantiate model class" ] }, { "cell_type": "code", "execution_count": 2, "id": "596726bb", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:34:35.686158Z", "iopub.status.busy": "2026-07-04T19:34:35.685940Z", "iopub.status.idle": "2026-07-04T19:34:35.688944Z", "shell.execute_reply": "2026-07-04T19:34:35.688592Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "class EnsembleAgeHumanMouse(LinearReferenceClock):\n", " pass\n", "\n" ] } ], "source": [ "def print_entire_class(cls):\n", " source = inspect.getsource(cls)\n", " print(source)\n", "\n", "print_entire_class(pya.models.EnsembleAgeHumanMouse)" ] }, { "cell_type": "code", "execution_count": 3, "id": "f91115e8", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:34:35.690204Z", "iopub.status.busy": "2026-07-04T19:34:35.690132Z", "iopub.status.idle": "2026-07-04T19:34:35.691885Z", "shell.execute_reply": "2026-07-04T19:34:35.691540Z" } }, "outputs": [], "source": [ "model = pya.models.EnsembleAgeHumanMouse()" ] }, { "cell_type": "markdown", "id": "fc745769", "metadata": {}, "source": [ "## Define clock metadata" ] }, { "cell_type": "code", "execution_count": 4, "id": "d9229f62", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:34:35.693133Z", "iopub.status.busy": "2026-07-04T19:34:35.693046Z", "iopub.status.idle": "2026-07-04T19:34:35.695208Z", "shell.execute_reply": "2026-07-04T19:34:35.694828Z" } }, "outputs": [], "source": [ "model.metadata[\"clock_name\"] = \"ensembleagehumanmouse\"\n", "model.metadata[\"data_type\"] = \"DNA methylation\" # Paper: EnsembleAge integrates predictions from multiple penalized models.\n", "model.metadata[\"species\"] = \"Homo sapiens and Mus musculus\" # Paper: A merged human-mouse dataset enabled cross-species predictions.\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\"] = \"Cross-species static EnsembleAge model trained on merged human and mouse methylation data; age is normalized by species maximum lifespan.\"\n", "model.metadata[\"research_only\"] = None\n", "model.metadata[\"tissue\"] = [\"multi-tissue\", \"whole blood\"] # Paper: The human dataset consisted of 81 blood samples; mouse data covered various tissues.\n", "model.metadata[\"predicts\"] = [\"relative age\"] # Paper: EnsembleAge integrates predictions from multiple penalized models.\n", "model.metadata[\"training_target\"] = [\"relative age\"] # Paper: Age was normalized by maximum species lifespan.\n", "model.metadata[\"unit\"] = [\"relative age\"] # Paper: HumanMouse clocks predict relative age (age/maximum species lifespan).\n", "model.metadata[\"model_type\"] = \"elastic net regression\" # Paper: The clocks were trained using ridge, lasso, and elastic net regression.\n", "model.metadata[\"platform\"] = [\"mammalian methylation array\"] # Paper: The DNA methylation data used in this study were generated using either the Mammal40k or Mammal320k BeadChip platforms.\n", "model.metadata[\"population\"] = \"humans and mice\" # Paper: Mouse and human methylation data were combined for cross-species predictions.\n", "model.metadata[\"journal\"] = \"GeroScience\"\n", "model.metadata[\"last_author\"] = \"Steve Horvath\"\n", "model.metadata[\"n_features\"] = 100\n", "model.metadata[\"citations\"] = 3\n", "model.metadata[\"citations_date\"] = \"2026-07-05\"\n" ] }, { "cell_type": "markdown", "id": "34c8c0c7", "metadata": {}, "source": [ "## Download clock dependencies" ] }, { "cell_type": "code", "execution_count": 5, "id": "8c43a8a1", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:34:35.696570Z", "iopub.status.busy": "2026-07-04T19:34:35.696488Z", "iopub.status.idle": "2026-07-04T19:34:35.858102Z", "shell.execute_reply": "2026-07-04T19:34:35.857414Z" } }, "outputs": [ { "data": { "text/plain": [ "0" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "supplementary_url = \"https://raw.githubusercontent.com/Duzhaozhen/OmniAge/c10fbe8cb92957520fbff1d55ae1def0691252e5/OmniAgePy/src/omniage/data/EnsembleAge/EnsembleAge_HumanMouse_HumanMouse_coefs.csv\"\n", "supplementary_file_name = \"coefficients.csv\"\n", "os.system(f\"curl -sL -o {supplementary_file_name} {supplementary_url}\")" ] }, { "cell_type": "markdown", "id": "719af326", "metadata": {}, "source": [ "## Load features" ] }, { "cell_type": "code", "execution_count": 6, "id": "64a4fac2", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:34:35.859936Z", "iopub.status.busy": "2026-07-04T19:34:35.859806Z", "iopub.status.idle": "2026-07-04T19:34:35.866906Z", "shell.execute_reply": "2026-07-04T19:34:35.866283Z" } }, "outputs": [], "source": [ "df = pd.read_csv('coefficients.csv')\n", "if str(df.columns[0]).startswith('Unnamed'):\n", " df = df.iloc[:, 1:]\n", "mask = df['probe'].astype(str).str.lower().isin(['intercept', '(intercept)'])\n", "intercept_value = float(df.loc[mask, 'coef'].iloc[0]) if mask.any() else 0.0\n", "coef_df = df.loc[~mask].reset_index(drop=True)\n", "model.features = coef_df['probe'].tolist()" ] }, { "cell_type": "markdown", "id": "f9c9a8bd", "metadata": {}, "source": [ "## Load weights into base model" ] }, { "cell_type": "code", "execution_count": 7, "id": "1cf7ab25", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:34:35.868665Z", "iopub.status.busy": "2026-07-04T19:34:35.868545Z", "iopub.status.idle": "2026-07-04T19:34:35.871508Z", "shell.execute_reply": "2026-07-04T19:34:35.870926Z" } }, "outputs": [], "source": [ "weights = torch.tensor(coef_df['coef'].tolist()).unsqueeze(0).float()\n", "intercept = torch.tensor([intercept_value]).float()" ] }, { "cell_type": "code", "execution_count": 8, "id": "3751b4b1", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:34:35.872890Z", "iopub.status.busy": "2026-07-04T19:34:35.872771Z", "iopub.status.idle": "2026-07-04T19:34:35.875542Z", "shell.execute_reply": "2026-07-04T19:34:35.875007Z" } }, "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": "49bf5598", "metadata": {}, "source": [ "## Load reference values" ] }, { "cell_type": "code", "execution_count": 9, "id": "060b4e0f", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:34:35.877338Z", "iopub.status.busy": "2026-07-04T19:34:35.877196Z", "iopub.status.idle": "2026-07-04T19:34:35.879255Z", "shell.execute_reply": "2026-07-04T19:34:35.878789Z" } }, "outputs": [], "source": [ "model.reference_values = None" ] }, { "cell_type": "markdown", "id": "610ac906", "metadata": {}, "source": [ "## Load preprocess and postprocess objects" ] }, { "cell_type": "code", "execution_count": 10, "id": "12e51c7a", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:34:35.880548Z", "iopub.status.busy": "2026-07-04T19:34:35.880453Z", "iopub.status.idle": "2026-07-04T19:34:35.882040Z", "shell.execute_reply": "2026-07-04T19:34:35.881604Z" } }, "outputs": [], "source": [ "model.preprocess_name = None\n", "model.preprocess_dependencies = None" ] }, { "cell_type": "code", "execution_count": 11, "id": "f372fd5b", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:34:35.883419Z", "iopub.status.busy": "2026-07-04T19:34:35.883334Z", "iopub.status.idle": "2026-07-04T19:34:35.885256Z", "shell.execute_reply": "2026-07-04T19:34:35.884855Z" } }, "outputs": [], "source": [ "model.postprocess_name = None\n", "model.postprocess_dependencies = None" ] }, { "cell_type": "markdown", "id": "8125ae04", "metadata": {}, "source": [ "## Check all clock parameters" ] }, { "cell_type": "code", "execution_count": 12, "id": "43a20bfb", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:34:35.886553Z", "iopub.status.busy": "2026-07-04T19:34:35.886472Z", "iopub.status.idle": "2026-07-04T19:34:35.890121Z", "shell.execute_reply": "2026-07-04T19:34:35.889695Z" } }, "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, Amin, et al. \"EnsembleAge: an ensemble of epigenetic '\n", " 'clocks for robust age estimation.\" GeroScience (2025).',\n", " 'clock_name': 'ensembleagehumanmouse',\n", " 'data_type': 'methylation',\n", " 'doi': 'https://doi.org/10.1007/s11357-025-01808-1',\n", " 'notes': None,\n", " 'research_only': None,\n", " 'species': 'Homo sapiens',\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: ['cg00001364', 'cg00001582', 'cg00003994', 'cg00005112', 'cg00051782', 'cg00060304', 'cg00066554', 'cg00067884', 'cg00073543', 'cg00079224', 'cg00084577', 'cg00091964', 'cg00096922', 'cg00109076', 'cg00109300', 'cg00116234', 'cg00146676', 'cg00158333', 'cg00159243', 'cg00167491', 'cg00187380', 'cg00211337', 'cg00216659', 'cg00247020', 'cg00271154', 'cg00272971', 'cg00297075', 'cg00314427', 'cg00323965', 'cg00331096']... [Total elements: 2252]\n", "base_model_features: None\n", "\n", "%==================================== Model Details ====================================%\n", "Model Structure:\n", "\n", "base_model: LinearModel(\n", " (linear): Linear(in_features=2252, out_features=1, bias=True)\n", ")\n", "\n", "%==================================== Model Details ====================================%\n", "Model Parameters and Weights:\n", "\n", "base_model.linear.weight: [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.02849973551928997, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -0.27547580003738403, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]... [Tensor of shape torch.Size([1, 2252])]\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "base_model.linear.bias: tensor([-0.5651])\n", "\n", "%==================================== Model Details ====================================%\n", "\n" ] } ], "source": [ "pya.utils.print_model_details(model)" ] }, { "cell_type": "markdown", "id": "6a0e8621", "metadata": {}, "source": [ "## Basic test" ] }, { "cell_type": "code", "execution_count": 13, "id": "4d2655ef", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:34:35.891852Z", "iopub.status.busy": "2026-07-04T19:34:35.891743Z", "iopub.status.idle": "2026-07-04T19:34:35.896802Z", "shell.execute_reply": "2026-07-04T19:34:35.896477Z" } }, "outputs": [ { "data": { "text/plain": [ "tensor([[-1.0967],\n", " [ 0.8136],\n", " [-3.3391],\n", " [-0.1142],\n", " [-1.4556],\n", " [ 2.6708],\n", " [-3.5248],\n", " [-2.2007],\n", " [-4.3380],\n", " [-1.6859]], dtype=torch.float64, grad_fn=)" ] }, "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": "004e34f8", "metadata": {}, "source": [ "## Save torch model" ] }, { "cell_type": "code", "execution_count": 14, "id": "5249b193", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:34:35.898442Z", "iopub.status.busy": "2026-07-04T19:34:35.898349Z", "iopub.status.idle": "2026-07-04T19:34:35.902267Z", "shell.execute_reply": "2026-07-04T19:34:35.901826Z" } }, "outputs": [], "source": [ "torch.save(model, f\"../weights/{model.metadata['clock_name']}.pt\")" ] }, { "cell_type": "markdown", "id": "c4016af5", "metadata": {}, "source": [ "## Clear directory\n", "" ] }, { "cell_type": "code", "execution_count": 15, "id": "933ba5a7", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:34:35.903562Z", "iopub.status.busy": "2026-07-04T19:34:35.903479Z", "iopub.status.idle": "2026-07-04T19:34:35.907178Z", "shell.execute_reply": "2026-07-04T19:34:35.906731Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Deleted file: coefficients.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": "Python 3 (ipykernel)", "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.13.11" } }, "nbformat": 4, "nbformat_minor": 5 }