{ "cells": [ { "cell_type": "markdown", "id": "2f04eee0-5928-4e74-a754-6dc2e528810c", "metadata": {}, "source": [ "# MammalianLifespan" ] }, { "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": 1, "id": "4adfb4de-cd79-4913-a1af-9e23e9e236c9", "metadata": { "execution": { "iopub.execute_input": "2025-04-07T18:02:45.960676Z", "iopub.status.busy": "2025-04-07T18:02:45.960314Z", "iopub.status.idle": "2025-04-07T18:02:47.353828Z", "shell.execute_reply": "2025-04-07T18:02:47.353514Z" } }, "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-07T18:02:47.355528Z", "iopub.status.busy": "2025-04-07T18:02:47.355313Z", "iopub.status.idle": "2025-04-07T18:02:47.363690Z", "shell.execute_reply": "2025-04-07T18:02:47.363417Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "class MammalianLifespan(pyagingModel):\n", " def __init__(self):\n", " super().__init__()\n", "\n", " def preprocess(self, x):\n", " return x\n", "\n", " def postprocess(self, x):\n", " \"\"\"\n", " Applies an anti-log transformation.\n", " \"\"\"\n", " return torch.exp(x)\n", "\n" ] } ], "source": [ "def print_entire_class(cls):\n", " source = inspect.getsource(cls)\n", " print(source)\n", "\n", "print_entire_class(pya.models.MammalianLifespan)" ] }, { "cell_type": "code", "execution_count": 3, "id": "78536494-f1d9-44de-8583-c89a310d2307", "metadata": { "execution": { "iopub.execute_input": "2025-04-07T18:02:47.364994Z", "iopub.status.busy": "2025-04-07T18:02:47.364911Z", "iopub.status.idle": "2025-04-07T18:02:47.366564Z", "shell.execute_reply": "2025-04-07T18:02:47.366333Z" } }, "outputs": [], "source": [ "model = pya.models.MammalianLifespan()" ] }, { "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-07T18:02:47.367840Z", "iopub.status.busy": "2025-04-07T18:02:47.367757Z", "iopub.status.idle": "2025-04-07T18:02:47.369735Z", "shell.execute_reply": "2025-04-07T18:02:47.369481Z" } }, "outputs": [], "source": [ "model.metadata[\"clock_name\"] = \"mammalianlifespan\"\n", "model.metadata[\"data_type\"] = \"DNA methylation\" # Paper: The model is based on DNA methylation measurements.\n", "model.metadata[\"species\"] = \"multiple species\" # Paper: The study samples are multi.\n", "model.metadata[\"year\"] = 2024\n", "model.metadata[\"approved_by_author\"] = \"⌛\"\n", "model.metadata[\"citation\"] = \"Li, Caesar Z., et al. \\\"Epigenetic predictors of species maximum life span and other life-history traits in mammals.\\\" Science Advances 10.23 (2024): eadm7273.\"\n", "model.metadata[\"doi\"] = \"https://doi.org/10.1126/sciadv.adm7273\"\n", "model.metadata[\"notes\"] = \"Pan-mammalian tissue-agnostic elastic-net predictor fitted to log species maximum life span from conserved CpG methylation; pyaging exponentiates the linear output to years.\"\n", "model.metadata[\"research_only\"] = None\n", "model.metadata[\"tissue\"] = [\"multi-tissue\"] # Paper: These samples spanned 59 unique tissue types and originated from 348 distinct mammalian species across 25 taxonomic orders.\n", "model.metadata[\"predicts\"] = [\"species maximum lifespan\"] # Paper: We will refer to the predicted maximum life span, expressed in log years, as either the epigenetic maximum life span or DNAm maximum life span.\n", "model.metadata[\"training_target\"] = [\"species maximum lifespan\"] # Paper: We used three distinct penalized regression models to predict the log-transformed values of maximum life span, gestation time, and age at sexual maturity for each species.\n", "model.metadata[\"unit\"] = [\"years\"] # Paper: We will refer to the predicted maximum life span, expressed in log years, as either the epigenetic maximum life span or DNAm maximum life span.\n", "model.metadata[\"model_type\"] = \"elastic net regression\" # Paper: First, we used elastic net regression models to predict maximum life span using both CpG methylation data and taxonomic order indicators.\n", "model.metadata[\"platform\"] = [\"Horvath MammalMethylChip40\"] # Paper: All data were generated using the mammalian methylation array (HorvathMammalMethylChip40), which provides high sequencing depth of highly conserved CpGs in mammals.\n", "model.metadata[\"population\"] = \"multiple mammalian species\" # Paper: Leveraging our publicly accessible data from the Mammalian Methylation Consortium, we focused on highly conserved cytosine methylation profiles from n = 15,000 DNA samples. These samples spanned 59 unique tissue types and originated from 348 distinct mammalian species across 25 taxonomic orders.\n", "model.metadata[\"journal\"] = \"Science Advances\"\n", "model.metadata[\"last_author\"] = \"Steve Horvath\"\n", "model.metadata[\"n_features\"] = 152 # Paper: The official LifespanPredictor_40K_Li2021.csv contains 152 nonzero non-intercept CpG coefficients.\n", "model.metadata[\"citations\"] = 5\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": "60a207cd-1a40-43bd-a93f-73de43358162", "metadata": {}, "source": [ "#### Download GitHub repository" ] }, { "cell_type": "code", "execution_count": 5, "id": "fc5e4c40-38e1-4db5-9dcd-15379d32aa90", "metadata": { "execution": { "iopub.execute_input": "2025-04-07T18:02:47.371056Z", "iopub.status.busy": "2025-04-07T18:02:47.370971Z", "iopub.status.idle": "2025-04-07T18:02:48.784711Z", "shell.execute_reply": "2025-04-07T18:02:48.784376Z" } }, "outputs": [ { "data": { "text/plain": [ "0" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "github_url = \"https://github.com/caeseriousli/MammalianMethylationPredictors.git\"\n", "github_folder_name = github_url.split('/')[-1].split('.')[0]\n", "os.system(f\"git clone {github_url}\")" ] }, { "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": "8a3d5de6-6303-487a-8b4d-e6345792f7be", "metadata": { "execution": { "iopub.execute_input": "2025-04-07T18:02:48.786289Z", "iopub.status.busy": "2025-04-07T18:02:48.786178Z", "iopub.status.idle": "2025-04-07T18:02:48.795076Z", "shell.execute_reply": "2025-04-07T18:02:48.794785Z" } }, "outputs": [], "source": [ "df = pd.read_csv('MammalianMethylationPredictors/Predictors/LifespanPredictor_40K_Li2021.csv')\n", "df['feature'] = df['CpG']\n", "df['coefficient'] = df['Coefficient']\n", "df = df[df.Coefficient != 0]\n", "\n", "model.features = df['feature'][1:].tolist()" ] }, { "cell_type": "markdown", "id": "ee6d8fa0-4767-4c45-9717-eb1c95e2ddc0", "metadata": {}, "source": [ "## Load weights into base model" ] }, { "cell_type": "code", "execution_count": 7, "id": "e09b3463-4fd4-41b1-ac21-e63ddd223fe0", "metadata": { "execution": { "iopub.execute_input": "2025-04-07T18:02:48.796541Z", "iopub.status.busy": "2025-04-07T18:02:48.796451Z", "iopub.status.idle": "2025-04-07T18:02:48.798520Z", "shell.execute_reply": "2025-04-07T18:02:48.798269Z" } }, "outputs": [], "source": [ "weights = torch.tensor(df['coefficient'][1:].tolist()).unsqueeze(0)\n", "intercept = torch.tensor([df['coefficient'][0]])" ] }, { "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-07T18:02:48.799874Z", "iopub.status.busy": "2025-04-07T18:02:48.799784Z", "iopub.status.idle": "2025-04-07T18:02:48.801901Z", "shell.execute_reply": "2025-04-07T18:02:48.801647Z" } }, "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": 9, "id": "ade0f4c9-2298-4fc3-bb72-d200907dd731", "metadata": { "execution": { "iopub.execute_input": "2025-04-07T18:02:48.803212Z", "iopub.status.busy": "2025-04-07T18:02:48.803129Z", "iopub.status.idle": "2025-04-07T18:02:48.804672Z", "shell.execute_reply": "2025-04-07T18:02:48.804404Z" } }, "outputs": [], "source": [ "model.reference_values = [0.5] * len(model.features)" ] }, { "cell_type": "markdown", "id": "af3bcf7b-74a8-4d21-9ccb-4de0c2b0516b", "metadata": {}, "source": [ "## Load preprocess and postprocess objects" ] }, { "cell_type": "code", "execution_count": 10, "id": "7a22fb20-c605-424d-8efb-7620c2c0755c", "metadata": { "execution": { "iopub.execute_input": "2025-04-07T18:02:48.805882Z", "iopub.status.busy": "2025-04-07T18:02:48.805801Z", "iopub.status.idle": "2025-04-07T18:02:48.807253Z", "shell.execute_reply": "2025-04-07T18:02:48.807012Z" } }, "outputs": [], "source": [ "model.preprocess_name = None\n", "model.preprocess_dependencies = None" ] }, { "cell_type": "code", "execution_count": 11, "id": "ff4a21cb-cf41-44dc-9ed1-95cf8aa15772", "metadata": { "execution": { "iopub.execute_input": "2025-04-07T18:02:48.808914Z", "iopub.status.busy": "2025-04-07T18:02:48.808789Z", "iopub.status.idle": "2025-04-07T18:02:48.810395Z", "shell.execute_reply": "2025-04-07T18:02:48.810138Z" } }, "outputs": [], "source": [ "model.postprocess_name = 'anti_log'\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": 12, "id": "2168355c-47d9-475d-b816-49f65e74887c", "metadata": { "execution": { "iopub.execute_input": "2025-04-07T18:02:48.811618Z", "iopub.status.busy": "2025-04-07T18:02:48.811535Z", "iopub.status.idle": "2025-04-07T18:02:48.814854Z", "shell.execute_reply": "2025-04-07T18:02:48.814613Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "%==================================== Model Details ====================================%\n", "Model Attributes:\n", "\n", "training: True\n", "metadata: {'approved_by_author': '⌛',\n", " 'citation': 'Li, Caesar Z., et al. \"Epigenetic predictors of species maximum '\n", " 'lifespan and other life history traits in mammals.\" bioRxiv '\n", " '(2023): 2023-11.',\n", " 'clock_name': 'mammalianlifespan',\n", " 'data_type': 'methylation',\n", " 'doi': 'https://doi.org/10.1101/2023.11.02.565286',\n", " 'notes': None,\n", " 'research_only': None,\n", " 'species': 'multi',\n", " 'version': None,\n", " 'year': 2023}\n", "reference_values: [0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5]... [Total elements: 152]\n", "preprocess_name: None\n", "preprocess_dependencies: None\n", "postprocess_name: 'anti_log'\n", "postprocess_dependencies: None\n", "features: ['cg00039845', 'cg00300233', 'cg00810217', 'cg01020408', 'cg01266508', 'cg01309159', 'cg01786675', 'cg02476543', 'cg02574410', 'cg02725055', 'cg02871478', 'cg03230916', 'cg03264110', 'cg03280886', 'cg03528345', 'cg03537184', 'cg03684591', 'cg03820088', 'cg04065686', 'cg04118146', 'cg04313551', 'cg04324237', 'cg04486940', 'cg04499301', 'cg04725401', 'cg04918691', 'cg04958799', 'cg05035746', 'cg05039938', 'cg05151611']... [Total elements: 152]\n", "base_model_features: None\n", "\n", "%==================================== Model Details ====================================%\n", "Model Structure:\n", "\n", "base_model: LinearModel(\n", " (linear): Linear(in_features=152, out_features=1, bias=True)\n", ")\n", "\n", "%==================================== Model Details ====================================%\n", "Model Parameters and Weights:\n", "\n", "base_model.linear.weight: [0.04147933050990105, 0.4304673969745636, 0.07260479032993317, 0.10754379630088806, 0.05837688222527504, 0.21564741432666779, 0.22965361177921295, 0.0423436276614666, -0.6524762511253357, -0.3474166989326477, 0.05646226927638054, 0.046050943434238434, -0.03867235779762268, -0.14654619991779327, 0.29777470231056213, -0.22357487678527832, 0.19166646897792816, 0.015969855710864067, 0.12260589003562927, 0.07850058376789093, 0.11844679713249207, 0.1271219253540039, -0.3257320821285248, -0.0814819186925888, 0.1456708163022995, 0.037799667567014694, 0.19944973289966583, -0.14140872657299042, -0.0007183622219599783, 0.28238773345947266]... [Tensor of shape torch.Size([1, 152])]\n", "base_model.linear.bias: tensor([-2.8285])\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": 13, "id": "936b9877-d076-4ced-99aa-e8d4c58c5caf", "metadata": { "execution": { "iopub.execute_input": "2025-04-07T18:02:48.816277Z", "iopub.status.busy": "2025-04-07T18:02:48.816155Z", "iopub.status.idle": "2025-04-07T18:02:48.819909Z", "shell.execute_reply": "2025-04-07T18:02:48.819653Z" } }, "outputs": [ { "data": { "text/plain": [ "tensor([[1.8245e+00],\n", " [7.4422e-04],\n", " [1.6053e+00],\n", " [2.6872e-01],\n", " [3.1673e-03],\n", " [2.4528e+01],\n", " [5.4639e+00],\n", " [1.6672e-02],\n", " [1.2177e-01],\n", " [1.5087e-02]], 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": "fe8299d7-9285-4e22-82fd-b664434b4369", "metadata": {}, "source": [ "## Save torch model" ] }, { "cell_type": "code", "execution_count": 14, "id": "5ef2fa8d-c80b-4fdd-8555-79c0d541788e", "metadata": { "execution": { "iopub.execute_input": "2025-04-07T18:02:48.821162Z", "iopub.status.busy": "2025-04-07T18:02:48.821083Z", "iopub.status.idle": "2025-04-07T18:02:48.823582Z", "shell.execute_reply": "2025-04-07T18:02:48.823330Z" } }, "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": 15, "id": "11aeaa70-44c0-42f9-86d7-740e3849a7a6", "metadata": { "execution": { "iopub.execute_input": "2025-04-07T18:02:48.824844Z", "iopub.status.busy": "2025-04-07T18:02:48.824751Z", "iopub.status.idle": "2025-04-07T18:02:48.833418Z", "shell.execute_reply": "2025-04-07T18:02:48.833160Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Deleted folder: MammalianMethylationPredictors\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", "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 }