{ "cells": [ { "cell_type": "markdown", "id": "2f04eee0-5928-4e74-a754-6dc2e528810c", "metadata": {}, "source": [ "# YingDamAge" ] }, { "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": "2024-03-05T21:24:02.211552Z", "iopub.status.busy": "2024-03-05T21:24:02.211102Z", "iopub.status.idle": "2024-03-05T21:24:03.523239Z", "shell.execute_reply": "2024-03-05T21:24:03.522939Z" } }, "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": "2024-03-05T21:24:03.525076Z", "iopub.status.busy": "2024-03-05T21:24:03.524915Z", "iopub.status.idle": "2024-03-05T21:24:03.534595Z", "shell.execute_reply": "2024-03-05T21:24:03.534346Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "class YingDamAge(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.YingDamAge)" ] }, { "cell_type": "code", "execution_count": 3, "id": "78536494-f1d9-44de-8583-c89a310d2307", "metadata": { "execution": { "iopub.execute_input": "2024-03-05T21:24:03.536067Z", "iopub.status.busy": "2024-03-05T21:24:03.535985Z", "iopub.status.idle": "2024-03-05T21:24:03.537676Z", "shell.execute_reply": "2024-03-05T21:24:03.537459Z" } }, "outputs": [], "source": [ "model = pya.models.YingDamAge()" ] }, { "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": "2024-03-05T21:24:03.539130Z", "iopub.status.busy": "2024-03-05T21:24:03.539058Z", "iopub.status.idle": "2024-03-05T21:24:03.541106Z", "shell.execute_reply": "2024-03-05T21:24:03.540883Z" } }, "outputs": [], "source": [ "model.metadata[\"clock_name\"] = \"yingdamage\"\n", "model.metadata[\"data_type\"] = \"DNA methylation\" # Paper: All three clocks use whole-blood DNA-methylation beta values.\n", "model.metadata[\"species\"] = \"Homo sapiens\" # Paper: The models were trained in human Generation Scotland blood samples.\n", "model.metadata[\"year\"] = 2024\n", "model.metadata[\"approved_by_author\"] = \"⌛\"\n", "model.metadata[\"citation\"] = \"Ying, K., Liu, H., Tarkhov, A.E. et al. Causality-enriched epigenetic age uncouples damage and adaptation. Nature Aging 4, 231–246 (2024).\"\n", "model.metadata[\"doi\"] = \"https://doi.org/10.1038/s43587-023-00557-0\"\n", "model.metadata[\"notes\"] = \"Causality-enriched age predictor restricted to damaging age-related CpGs, with feature penalties weighted by EWMR causality scores.\"\n", "model.metadata[\"research_only\"] = None\n", "model.metadata[\"tissue\"] = [\"whole blood\"] # Paper: The model was trained in whole-blood methylation.\n", "model.metadata[\"predicts\"] = [\"damaging epigenetic age\"] # Paper: DamAge is designed as a biomarker of age-related damaging methylation changes.\n", "model.metadata[\"training_target\"] = [\"chronological age\"] # Paper: All three causality-enriched elastic-net models were trained to predict chronological age.\n", "model.metadata[\"unit\"] = [\"years\"] # Paper: Model selection used mean absolute error in years against chronological age.\n", "model.metadata[\"model_type\"] = \"causality-weighted elastic net regression\" # Paper: Feature-specific elastic-net penalty factors were assigned from each CpG's causality score.\n", "model.metadata[\"platform\"] = [\"Illumina 450K\"] # Paper: Training used Generation Scotland whole-blood methylation at CpGs available to the 450K-based analysis.\n", "model.metadata[\"population\"] = \"adults\" # Paper: Age-related methylation was estimated in 7,036 Generation Scotland participants aged 18–93, and 2,664 blood samples were used for clock training.\n", "model.metadata[\"journal\"] = \"Nature Aging\"\n", "model.metadata[\"last_author\"] = \"Vadim N. Gladyshev\"\n", "model.metadata[\"n_features\"] = 1089\n", "model.metadata[\"citations\"] = 183\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": "fbacbbc5-7cf1-41bd-81c4-45adde992de6", "metadata": {}, "source": [ "#### Download directly with curl" ] }, { "cell_type": "code", "execution_count": 5, "id": "348e113d-a00a-481d-84ac-e8459a4a5050", "metadata": { "execution": { "iopub.execute_input": "2024-03-05T21:24:03.542569Z", "iopub.status.busy": "2024-03-05T21:24:03.542473Z", "iopub.status.idle": "2024-03-05T21:24:03.626893Z", "shell.execute_reply": "2024-03-05T21:24:03.626623Z" } }, "outputs": [ { "data": { "text/plain": [ "0" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "supplementary_url = \"https://static-content.springer.com/esm/art%3A10.1038%2Fs43587-023-00557-0/MediaObjects/43587_2023_557_MOESM6_ESM.zip\"\n", "supplementary_file_name = \"43587_2023_557_MOESM6_ESM.zip\"\n", "os.system(f\"curl -o {supplementary_file_name} {supplementary_url}\")\n", "os.system(f'unzip {supplementary_file_name}')" ] }, { "cell_type": "markdown", "id": "5035b180-3d1b-4432-8ebe-b9c92bd93a7f", "metadata": {}, "source": [ "## Load features" ] }, { "cell_type": "markdown", "id": "1c756bdc-1646-4915-b91d-4da228a02fbc", "metadata": {}, "source": [ "#### From CSV file" ] }, { "cell_type": "code", "execution_count": 6, "id": "388283a9-923f-4219-b018-e59cb951ffae", "metadata": { "execution": { "iopub.execute_input": "2024-03-05T21:24:03.628565Z", "iopub.status.busy": "2024-03-05T21:24:03.628461Z", "iopub.status.idle": "2024-03-05T21:24:03.632172Z", "shell.execute_reply": "2024-03-05T21:24:03.631937Z" } }, "outputs": [], "source": [ "df = pd.read_csv('YingDamAge.csv')\n", "df['feature'] = df['term']\n", "df['coefficient'] = df['estimate']\n", "model.features = df['feature'][1:].tolist()" ] }, { "cell_type": "markdown", "id": "5e3e30f8-4cae-4f82-98cf-927c55eea9df", "metadata": {}, "source": [ "## Load weights into base model" ] }, { "cell_type": "code", "execution_count": 7, "id": "051acf76-075a-44e9-91b4-7fd3a28cfbdf", "metadata": { "execution": { "iopub.execute_input": "2024-03-05T21:24:03.633688Z", "iopub.status.busy": "2024-03-05T21:24:03.633612Z", "iopub.status.idle": "2024-03-05T21:24:03.635646Z", "shell.execute_reply": "2024-03-05T21:24:03.635397Z" } }, "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": "2024-03-05T21:24:03.637102Z", "iopub.status.busy": "2024-03-05T21:24:03.637022Z", "iopub.status.idle": "2024-03-05T21:24:03.639147Z", "shell.execute_reply": "2024-03-05T21:24:03.638925Z" } }, "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": "2024-03-05T21:24:03.640642Z", "iopub.status.busy": "2024-03-05T21:24:03.640563Z", "iopub.status.idle": "2024-03-05T21:24:03.642135Z", "shell.execute_reply": "2024-03-05T21:24:03.641855Z" } }, "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": "2024-03-05T21:24:03.643510Z", "iopub.status.busy": "2024-03-05T21:24:03.643435Z", "iopub.status.idle": "2024-03-05T21:24:03.644942Z", "shell.execute_reply": "2024-03-05T21:24:03.644726Z" } }, "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": "2024-03-05T21:24:03.646307Z", "iopub.status.busy": "2024-03-05T21:24:03.646223Z", "iopub.status.idle": "2024-03-05T21:24:03.647719Z", "shell.execute_reply": "2024-03-05T21:24:03.647501Z" } }, "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": 12, "id": "2168355c-47d9-475d-b816-49f65e74887c", "metadata": { "execution": { "iopub.execute_input": "2024-03-05T21:24:03.649103Z", "iopub.status.busy": "2024-03-05T21:24:03.649030Z", "iopub.status.idle": "2024-03-05T21:24:03.652086Z", "shell.execute_reply": "2024-03-05T21:24:03.651862Z" } }, "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. \"Causality-enriched epigenetic age '\n", " 'uncouples damage and adaptation.\" Nature Aging (2024): 1-16.',),\n", " 'clock_name': 'yingdamage',\n", " 'data_type': 'methylation',\n", " 'doi': 'https://doi.org/10.1038/s43587-023-00557-0',\n", " 'notes': None,\n", " 'research_only': None,\n", " 'species': 'Homo sapiens',\n", " 'version': None,\n", " 'year': 2024}\n", "reference_values: None\n", "preprocess_name: None\n", "preprocess_dependencies: None\n", "postprocess_name: None\n", "postprocess_dependencies: None\n", "features: ['cg00003994', 'cg00023464', 'cg00049440', 'cg00052482', 'cg00073543', 'cg00084338', 'cg00115654', 'cg00117599', 'cg00192773', 'cg00228017', 'cg00296038', 'cg00300637', 'cg00310410', 'cg00330279', 'cg00332802', 'cg00346985', 'cg00423487', 'cg00462168', 'cg00488692', 'cg00512563', 'cg00523379', 'cg00534318', 'cg00554993', 'cg00563845', 'cg00603274', 'cg00612299', 'cg00614360', 'cg00645579', 'cg00655552', 'cg00697033']... [Total elements: 1089]\n", "base_model_features: None\n", "\n", "%==================================== Model Details ====================================%\n", "Model Structure:\n", "\n", "base_model: LinearModel(\n", " (linear): Linear(in_features=1089, out_features=1, bias=True)\n", ")\n", "\n", "%==================================== Model Details ====================================%\n", "Model Parameters and Weights:\n", "\n", "base_model.linear.weight: [0.1111111119389534, 0.1420900523662567, 0.8157786130905151, -4.8587541580200195, 0.47707557678222656, 0.5002065300941467, 0.39611729979515076, 0.9855431914329529, 0.2023957073688507, 0.35894259810447693, 0.05865344777703285, -1.7170811891555786, 0.6014043688774109, -2.180171012878418, 0.9566295146942139, 0.4613795876502991, 0.8703015446662903, 0.1672862470149994, 0.06815365701913834, 0.15401731431484222, -3.003317356109619, 0.026848409324884415, -7.108214378356934, -5.615413665771484, 0.0425444021821022, 0.48533663153648376, 0.15448161959648132, 0.4560099244117737, -4.907559871673584, 0.8859975337982178]... [Tensor of shape torch.Size([1, 1089])]\n", "base_model.linear.bias: tensor([543.4316])\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": "2024-03-05T21:24:03.653676Z", "iopub.status.busy": "2024-03-05T21:24:03.653568Z", "iopub.status.idle": "2024-03-05T21:24:03.657640Z", "shell.execute_reply": "2024-03-05T21:24:03.657364Z" } }, "outputs": [ { "data": { "text/plain": [ "tensor([[584.9497],\n", " [565.7351],\n", " [780.7145],\n", " [383.1862],\n", " [373.4299],\n", " [484.9948],\n", " [714.8078],\n", " [755.3972],\n", " [452.7687],\n", " [641.0902]], 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": "2024-03-05T21:24:03.659204Z", "iopub.status.busy": "2024-03-05T21:24:03.659121Z", "iopub.status.idle": "2024-03-05T21:24:03.661508Z", "shell.execute_reply": "2024-03-05T21:24:03.661255Z" } }, "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": "2024-03-05T21:24:03.662928Z", "iopub.status.busy": "2024-03-05T21:24:03.662849Z", "iopub.status.idle": "2024-03-05T21:24:03.666229Z", "shell.execute_reply": "2024-03-05T21:24:03.666006Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Deleted file: 43587_2023_557_MOESM6_ESM.zip\n", "Deleted file: YingCausAge.csv\n", "Deleted file: YingDamAge.csv\n", "Deleted file: YingAdaptAge.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", "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.17" } }, "nbformat": 4, "nbformat_minor": 5 }