{ "cells": [ { "cell_type": "markdown", "id": "2f04eee0-5928-4e74-a754-6dc2e528810c", "metadata": {}, "source": [ "# Mammalian1" ] }, { "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-07T17:52:25.879427Z", "iopub.status.busy": "2025-04-07T17:52:25.879024Z", "iopub.status.idle": "2025-04-07T17:52:27.262351Z", "shell.execute_reply": "2025-04-07T17:52:27.262006Z" } }, "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:52:27.264090Z", "iopub.status.busy": "2025-04-07T17:52:27.263870Z", "iopub.status.idle": "2025-04-07T17:52:27.271225Z", "shell.execute_reply": "2025-04-07T17:52:27.270947Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "class Mammalian1(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-logarithmic transformation with an offset of -2.\n", " \"\"\"\n", " return torch.exp(x) - 2\n", "\n" ] } ], "source": [ "def print_entire_class(cls):\n", " source = inspect.getsource(cls)\n", " print(source)\n", "\n", "print_entire_class(pya.models.Mammalian1)" ] }, { "cell_type": "code", "execution_count": 3, "id": "78536494-f1d9-44de-8583-c89a310d2307", "metadata": { "execution": { "iopub.execute_input": "2025-04-07T17:52:27.272501Z", "iopub.status.busy": "2025-04-07T17:52:27.272412Z", "iopub.status.idle": "2025-04-07T17:52:27.274021Z", "shell.execute_reply": "2025-04-07T17:52:27.273779Z" } }, "outputs": [], "source": [ "model = pya.models.Mammalian1()" ] }, { "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:52:27.275343Z", "iopub.status.busy": "2025-04-07T17:52:27.275261Z", "iopub.status.idle": "2025-04-07T17:52:27.277257Z", "shell.execute_reply": "2025-04-07T17:52:27.276995Z" } }, "outputs": [], "source": [ "model.metadata[\"clock_name\"] = \"mammalian1\"\n", "model.metadata[\"data_type\"] = \"DNA methylation\" # Paper: methylation\n", "model.metadata[\"species\"] = \"multiple species\" # Paper: multi\n", "model.metadata[\"year\"] = 2023\n", "model.metadata[\"approved_by_author\"] = \"⌛\"\n", "model.metadata[\"citation\"] = \"Lu, A. T., et al. \\\"Universal DNA methylation age across mammalian tissues.\\\" Nature Aging 3.9 (2023): 1144-1166.\"\n", "model.metadata[\"doi\"] = \"https://doi.org/10.1038/s43587-023-00462-6\"\n", "model.metadata[\"notes\"] = \"Universal pan-mammalian clock 1: elastic-net regression of log-transformed chronological age on conserved mammalian-array CpGs, back-transformed to years.\"\n", "model.metadata[\"research_only\"] = None\n", "model.metadata[\"tissue\"] = [\"multi-tissue\"] # Paper: multi-tissue\n", "model.metadata[\"predicts\"] = [\"chronological age\"] # Paper: The official inverse transformation returns DNAm chronological age in years.\n", "model.metadata[\"training_target\"] = [\"chronological age\"] # Paper: log-transformed chronological age\n", "model.metadata[\"unit\"] = [\"years\"] # Paper: The official inverse transformation returns DNAm chronological age in years.\n", "model.metadata[\"model_type\"] = \"elastic net regression\" # Paper: Elastic net\n", "model.metadata[\"platform\"] = [\"Horvath MammalMethylChip40\"] # Paper: HorvathMammalMethylChip40\n", "model.metadata[\"population\"] = \"multiple mammalian species\" # Paper: 11,754 samples from 185 mammalian species, prenatal to 139 years\n", "model.metadata[\"journal\"] = \"Nature Aging\"\n", "model.metadata[\"last_author\"] = \"Steve Horvath\"\n", "model.metadata[\"n_features\"] = 335\n", "model.metadata[\"citations\"] = 390\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": "5881f33e-0486-45d1-bd87-9c995f47ca62", "metadata": {}, "source": [ "#### Download GitHub repository" ] }, { "cell_type": "code", "execution_count": 5, "id": "e85525f7-6da4-4962-a7d5-0607e76eea33", "metadata": { "execution": { "iopub.execute_input": "2025-04-07T17:52:27.278605Z", "iopub.status.busy": "2025-04-07T17:52:27.278524Z", "iopub.status.idle": "2025-04-07T17:54:14.063611Z", "shell.execute_reply": "2025-04-07T17:54:14.063129Z" } }, "outputs": [ { "data": { "text/plain": [ "0" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "github_url = \"https://github.com/shorvath/MammalianMethylationConsortium.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-07T17:54:14.066374Z", "iopub.status.busy": "2025-04-07T17:54:14.066025Z", "iopub.status.idle": "2025-04-07T17:54:14.072573Z", "shell.execute_reply": "2025-04-07T17:54:14.072206Z" } }, "outputs": [], "source": [ "df = pd.read_csv('MammalianMethylationConsortium/UniversalPanMammalianClock/ClockParameters/clock1.csv')\n", "df['feature'] = df['var']\n", "df['coefficient'] = df['beta_clock1']\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-07T17:54:14.074085Z", "iopub.status.busy": "2025-04-07T17:54:14.073988Z", "iopub.status.idle": "2025-04-07T17:54:14.076024Z", "shell.execute_reply": "2025-04-07T17:54:14.075774Z" } }, "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-07T17:54:14.077367Z", "iopub.status.busy": "2025-04-07T17:54:14.077278Z", "iopub.status.idle": "2025-04-07T17:54:14.079581Z", "shell.execute_reply": "2025-04-07T17:54:14.079343Z" } }, "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-07T17:54:14.080784Z", "iopub.status.busy": "2025-04-07T17:54:14.080705Z", "iopub.status.idle": "2025-04-07T17:54:14.082183Z", "shell.execute_reply": "2025-04-07T17:54:14.081924Z" } }, "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": 10, "id": "7a22fb20-c605-424d-8efb-7620c2c0755c", "metadata": { "execution": { "iopub.execute_input": "2025-04-07T17:54:14.083447Z", "iopub.status.busy": "2025-04-07T17:54:14.083365Z", "iopub.status.idle": "2025-04-07T17:54:14.084680Z", "shell.execute_reply": "2025-04-07T17:54:14.084455Z" } }, "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-07T17:54:14.085902Z", "iopub.status.busy": "2025-04-07T17:54:14.085803Z", "iopub.status.idle": "2025-04-07T17:54:14.087266Z", "shell.execute_reply": "2025-04-07T17:54:14.087037Z" } }, "outputs": [], "source": [ "model.postprocess_name = 'anti_logp2'\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-07T17:54:14.088406Z", "iopub.status.busy": "2025-04-07T17:54:14.088324Z", "iopub.status.idle": "2025-04-07T17:54:14.092557Z", "shell.execute_reply": "2025-04-07T17:54:14.092248Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "%==================================== Model Details ====================================%\n", "Model Attributes:\n", "\n", "training: True\n", "metadata: {'approved_by_author': '⌛',\n", " 'citation': 'Lu, A. T., et al. \"Universal DNA methylation age across '\n", " 'mammalian tissues.\" Nature aging 3.9 (2023): 1144-1166.',\n", " 'clock_name': 'mammalian1',\n", " 'data_type': 'methylation',\n", " 'doi': 'https://doi.org/10.1038/s43587-023-00462-6',\n", " 'notes': None,\n", " 'research_only': None,\n", " 'species': 'multi',\n", " 'version': None,\n", " 'year': 2023}\n", "reference_values: None\n", "preprocess_name: None\n", "preprocess_dependencies: None\n", "postprocess_name: 'anti_logp2'\n", "postprocess_dependencies: None\n", "features: ['cg00249943', 'cg00250826', 'cg00292639', 'cg00362836', 'cg00411555', 'cg00513357', 'cg00587168', 'cg00593462', 'cg00687674', 'cg00694357', 'cg00900456', 'cg00954002', 'cg01009870', 'cg01019040', 'cg01059743', 'cg01136078', 'cg01153166', 'cg01169686', 'cg01246498', 'cg01429475', 'cg01511232', 'cg01656216', 'cg01698540', 'cg01794235', 'cg01975510', 'cg02474352', 'cg02499612', 'cg02532525', 'cg02606236', 'cg02692845']... [Total elements: 335]\n", "base_model_features: None\n", "\n", "%==================================== Model Details ====================================%\n", "Model Structure:\n", "\n", "base_model: LinearModel(\n", " (linear): Linear(in_features=335, out_features=1, bias=True)\n", ")\n", "\n", "%==================================== Model Details ====================================%\n", "Model Parameters and Weights:\n", "\n", "base_model.linear.weight: [0.1527862846851349, 0.0027701049111783504, -0.12989148497581482, 0.048629630357027054, -0.03136558085680008, 0.09142599999904633, 0.055298686027526855, 0.4379110336303711, -0.1408686339855194, -0.808471143245697, -0.03339824452996254, -0.12297524511814117, 0.10108527541160583, -0.004560905043035746, -0.20634084939956665, -0.0016184860141947865, 0.07213742285966873, -0.03695621341466904, 0.052970658987760544, 0.17211447656154633, 0.037939656525850296, 0.04749084636569023, 0.0619727298617363, 0.04738111421465874, 0.05404146388173103, 0.055779341608285904, -0.04102899879217148, 0.1298285871744156, -0.020354116335511208, -0.0109869921579957]... [Tensor of shape torch.Size([1, 335])]\n", "base_model.linear.bias: tensor([1.4314])\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-07T17:54:14.093889Z", "iopub.status.busy": "2025-04-07T17:54:14.093797Z", "iopub.status.idle": "2025-04-07T17:54:14.099279Z", "shell.execute_reply": "2025-04-07T17:54:14.098988Z" } }, "outputs": [ { "data": { "text/plain": [ "tensor([[-1.9999e+00],\n", " [-1.2721e+00],\n", " [ 6.0199e+00],\n", " [ 1.5016e+00],\n", " [ 3.6253e+02],\n", " [ 1.1582e+01],\n", " [-1.8921e+00],\n", " [ 2.7133e+03],\n", " [ 2.1860e+01],\n", " [ 8.6071e+00]], 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-07T17:54:14.100586Z", "iopub.status.busy": "2025-04-07T17:54:14.100486Z", "iopub.status.idle": "2025-04-07T17:54:14.102917Z", "shell.execute_reply": "2025-04-07T17:54:14.102639Z" } }, "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-07T17:54:14.104269Z", "iopub.status.busy": "2025-04-07T17:54:14.104178Z", "iopub.status.idle": "2025-04-07T17:54:14.244927Z", "shell.execute_reply": "2025-04-07T17:54:14.244638Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Deleted folder: MammalianMethylationConsortium\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 }