{ "cells": [ { "cell_type": "markdown", "id": "cf58bcdf", "metadata": {}, "source": [ "# CVDWesterman" ] }, { "cell_type": "markdown", "id": "e44a46b8", "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": "d42bd7e5", "metadata": {}, "source": [ "Let's first import some packages:" ] }, { "cell_type": "code", "execution_count": 1, "id": "714014f8", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T20:25:18.783639Z", "iopub.status.busy": "2026-07-04T20:25:18.783340Z", "iopub.status.idle": "2026-07-04T20:25:20.933337Z", "shell.execute_reply": "2026-07-04T20:25:20.932817Z" } }, "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": "63f8302e", "metadata": {}, "source": [ "## Instantiate model class" ] }, { "cell_type": "code", "execution_count": 2, "id": "bf2f68fb", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T20:25:20.935292Z", "iopub.status.busy": "2026-07-04T20:25:20.935076Z", "iopub.status.idle": "2026-07-04T20:25:20.937956Z", "shell.execute_reply": "2026-07-04T20:25:20.937585Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "class CVDWesterman(LinearReferenceClock):\n", " def postprocess(self, x):\n", " \"\"\"Logistic transform to a CVD risk probability.\"\"\"\n", " return torch.sigmoid(x)\n", "\n" ] } ], "source": [ "def print_entire_class(cls):\n", " source = inspect.getsource(cls)\n", " print(source)\n", "\n", "print_entire_class(pya.models.CVDWesterman)" ] }, { "cell_type": "code", "execution_count": 3, "id": "ac4e326f", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T20:25:20.939157Z", "iopub.status.busy": "2026-07-04T20:25:20.939070Z", "iopub.status.idle": "2026-07-04T20:25:20.940546Z", "shell.execute_reply": "2026-07-04T20:25:20.940210Z" } }, "outputs": [], "source": [ "model = pya.models.CVDWesterman()" ] }, { "cell_type": "markdown", "id": "3e29493d", "metadata": {}, "source": [ "## Define clock metadata" ] }, { "cell_type": "code", "execution_count": 4, "id": "d49a8755", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T20:25:20.941831Z", "iopub.status.busy": "2026-07-04T20:25:20.941755Z", "iopub.status.idle": "2026-07-04T20:25:20.943834Z", "shell.execute_reply": "2026-07-04T20:25:20.943444Z" } }, "outputs": [], "source": [ "model.metadata[\"clock_name\"] = \"cvdwesterman\"\n", "model.metadata[\"data_type\"] = \"DNA methylation\" # Paper: DNA methylation cardiovascular risk score from blood cohorts.\n", "model.metadata[\"species\"] = \"Homo sapiens\" # Paper: DNA methylation cardiovascular risk score from blood cohorts.\n", "model.metadata[\"year\"] = 2020\n", "model.metadata[\"approved_by_author\"] = \"⌛\"\n", "model.metadata[\"citation\"] = \"Westerman, K. et al. Epigenomic assessment of cardiovascular disease risk and interactions with traditional risk metrics. Journal of the American Heart Association 9, e015299 (2020).\"\n", "model.metadata[\"doi\"] = \"https://doi.org/10.1161/jaha.119.015299\"\n", "model.metadata[\"notes\"] = \"Whole-blood DNA-methylation score for cardiovascular risk. The paper's final cross-study learner stacks cohort-specific elastic-net Cox models; the packaged pyaging implementation is a 235-CpG linear score followed by a sigmoid.\"\n", "model.metadata[\"research_only\"] = None\n", "model.metadata[\"tissue\"] = [\"whole blood\"] # Paper: DNA methylation data ... collected using the HumanMethylation450 platform.\n", "model.metadata[\"predicts\"] = [\"cardiovascular disease risk\"] # Paper: postprocess_name = 'sigmoid'\n", "model.metadata[\"training_target\"] = [\"cardiovascular disease\"] # Paper: CVD events included coronary heart disease, stroke, and death from CVD.\n", "model.metadata[\"unit\"] = [\"probability\"] # Paper: Logistic transform to a CVD risk probability.\n", "model.metadata[\"model_type\"] = \"elastic net Cox ensemble\" # Paper: Penalized Cox proportional hazards regressions with the elastic net penalty.\n", "model.metadata[\"platform\"] = [\"Illumina 450K\"] # Paper: Illumina HumanMethylation450 microarray platform\n", "model.metadata[\"population\"] = \"adults\" # Paper: WHI, FHS-JHU, and LBC were the initial training cohorts.\n", "model.metadata[\"journal\"] = \"Journal of the American Heart Association\"\n", "model.metadata[\"last_author\"] = \"José M. Ordovás\"\n", "model.metadata[\"n_features\"] = 235\n", "model.metadata[\"citations\"] = 53\n", "model.metadata[\"citations_date\"] = \"2026-07-05\"\n" ] }, { "cell_type": "markdown", "id": "8b9091c3", "metadata": {}, "source": [ "## Download clock dependencies" ] }, { "cell_type": "code", "execution_count": 5, "id": "11138ae8", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T20:25:20.944957Z", "iopub.status.busy": "2026-07-04T20:25:20.944892Z", "iopub.status.idle": "2026-07-04T20:25:21.274961Z", "shell.execute_reply": "2026-07-04T20:25:21.274139Z" } }, "outputs": [ { "data": { "text/plain": [ "0" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "os.system(f\"curl -sL -o coefficients.csv https://raw.githubusercontent.com/bio-learn/biolearn/180852e2bab473303cb85da627178b1695ee9d86/biolearn/data/CVD_Westermann.csv\")" ] }, { "cell_type": "markdown", "id": "e705eb35", "metadata": {}, "source": [ "## Load features" ] }, { "cell_type": "code", "execution_count": 6, "id": "78ac6cd0", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T20:25:21.280151Z", "iopub.status.busy": "2026-07-04T20:25:21.279312Z", "iopub.status.idle": "2026-07-04T20:25:21.289633Z", "shell.execute_reply": "2026-07-04T20:25:21.288258Z" } }, "outputs": [], "source": [ "df = pd.read_csv('coefficients.csv')\n", "mask = df['CpGmarker'].astype(str).str.lower().isin(['intercept', '(intercept)'])\n", "intercept_value = float(df.loc[mask, 'CoefficientTraining'].iloc[0]) if mask.any() else 0.0\n", "coef_df = df.loc[~mask].reset_index(drop=True)\n", "model.features = coef_df['CpGmarker'].tolist()" ] }, { "cell_type": "markdown", "id": "48174ee5", "metadata": {}, "source": [ "## Load weights into base model" ] }, { "cell_type": "code", "execution_count": 7, "id": "f2e98f1e", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T20:25:21.292689Z", "iopub.status.busy": "2026-07-04T20:25:21.292424Z", "iopub.status.idle": "2026-07-04T20:25:21.297083Z", "shell.execute_reply": "2026-07-04T20:25:21.296582Z" } }, "outputs": [], "source": [ "weights = torch.tensor(coef_df['CoefficientTraining'].tolist()).unsqueeze(0).float()\n", "intercept = torch.tensor([intercept_value]).float()" ] }, { "cell_type": "code", "execution_count": 8, "id": "c1b2de96", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T20:25:21.298716Z", "iopub.status.busy": "2026-07-04T20:25:21.298589Z", "iopub.status.idle": "2026-07-04T20:25:21.301406Z", "shell.execute_reply": "2026-07-04T20:25:21.300753Z" } }, "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": "785a8ea5", "metadata": {}, "source": [ "## Load reference values" ] }, { "cell_type": "code", "execution_count": 9, "id": "7e81598e", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T20:25:21.303014Z", "iopub.status.busy": "2026-07-04T20:25:21.302910Z", "iopub.status.idle": "2026-07-04T20:25:21.304561Z", "shell.execute_reply": "2026-07-04T20:25:21.304171Z" } }, "outputs": [], "source": [ "model.reference_values = None" ] }, { "cell_type": "markdown", "id": "2c050dfc", "metadata": {}, "source": [ "## Load preprocess and postprocess objects" ] }, { "cell_type": "code", "execution_count": 10, "id": "a3bcf4df", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T20:25:21.305858Z", "iopub.status.busy": "2026-07-04T20:25:21.305776Z", "iopub.status.idle": "2026-07-04T20:25:21.307465Z", "shell.execute_reply": "2026-07-04T20:25:21.307136Z" } }, "outputs": [], "source": [ "model.preprocess_name = None\n", "model.preprocess_dependencies = None" ] }, { "cell_type": "code", "execution_count": 11, "id": "719a7a51", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T20:25:21.308823Z", "iopub.status.busy": "2026-07-04T20:25:21.308735Z", "iopub.status.idle": "2026-07-04T20:25:21.311070Z", "shell.execute_reply": "2026-07-04T20:25:21.310220Z" } }, "outputs": [], "source": [ "model.postprocess_name = 'sigmoid'\n", "model.postprocess_dependencies = None" ] }, { "cell_type": "markdown", "id": "45e5021f", "metadata": {}, "source": [ "## Check all clock parameters" ] }, { "cell_type": "code", "execution_count": 12, "id": "6bb92439", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T20:25:21.313068Z", "iopub.status.busy": "2026-07-04T20:25:21.312943Z", "iopub.status.idle": "2026-07-04T20:25:21.317159Z", "shell.execute_reply": "2026-07-04T20:25:21.316616Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "%==================================== Model Details ====================================%\n", "Model Attributes:\n", "\n", "training: True\n", "metadata: {'approved_by_author': '⌛',\n", " 'citation': 'Westerman, Kenneth, et al. \"Epigenomic assessment of '\n", " 'cardiovascular disease risk and interactions with traditional '\n", " 'risk metrics.\" Journal of the American Heart Association 9.8 '\n", " '(2020): e015299.',\n", " 'clock_name': 'cvdwesterman',\n", " 'data_type': 'methylation',\n", " 'doi': 'https://doi.org/10.1161/JAHA.119.015299',\n", " 'notes': None,\n", " 'research_only': None,\n", " 'species': 'Homo sapiens',\n", " 'version': None,\n", " 'year': 2020}\n", "reference_values: None\n", "preprocess_name: None\n", "preprocess_dependencies: None\n", "postprocess_name: 'sigmoid'\n", "postprocess_dependencies: None\n", "features: ['cg13077366', 'cg13679303', 'cg19214707', 'cg18593317', 'cg03463778', 'cg26626449', 'cg05630272', 'cg23522872', 'cg12588880', 'cg13074055', 'cg02655711', 'cg12624197', 'cg05843457', 'cg10963061', 'cg12121643', 'cg23613051', 'cg26504835', 'cg23063825', 'cg25188006', 'cg00887153', 'cg16574737', 'cg25283121', 'cg23239574', 'cg25564433', 'cg10612096', 'cg13903421', 'cg16268165', 'cg00600477', 'cg10516993', 'cg03930209']... [Total elements: 235]\n", "base_model_features: None\n", "\n", "%==================================== Model Details ====================================%\n", "Model Structure:\n", "\n", "base_model: LinearModel(\n", " (linear): Linear(in_features=235, out_features=1, bias=True)\n", ")\n", "\n", "%==================================== Model Details ====================================%\n", "Model Parameters and Weights:\n", "\n", "base_model.linear.weight: [0.0023171070497483015, 0.0011196619598194957, -0.013891435228288174, -0.002025559078902006, -0.009562727063894272, 0.06509598344564438, -0.020258523523807526, 0.0033463360741734505, -0.007966549135744572, -0.010243932716548443, -0.01568872109055519, 0.028809623792767525, 0.002753776963800192, 0.019885685294866562, 0.047365110367536545, 0.037816889584064484, 0.0031414860859513283, -0.004254682920873165, 0.002840817905962467, 0.002047969028353691, 0.0016441689804196358, 0.010059863328933716, 0.013813807629048824, 0.002602970926091075, 0.0023500178940594196, 0.004787160083651543, -0.006558055058121681, 0.01796160265803337, 0.016836676746606827, 0.0022038749884814024]... [Tensor of shape torch.Size([1, 235])]\n", "base_model.linear.bias: tensor([0.])\n", "\n", "%==================================== Model Details ====================================%\n", "\n" ] } ], "source": [ "pya.utils.print_model_details(model)" ] }, { "cell_type": "markdown", "id": "f5bdf248", "metadata": {}, "source": [ "## Basic test" ] }, { "cell_type": "code", "execution_count": 13, "id": "22cd81c1", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T20:25:21.318602Z", "iopub.status.busy": "2026-07-04T20:25:21.318504Z", "iopub.status.idle": "2026-07-04T20:25:21.324451Z", "shell.execute_reply": "2026-07-04T20:25:21.323983Z" } }, "outputs": [ { "data": { "text/plain": [ "tensor([[0.3971],\n", " [0.6197],\n", " [0.7023],\n", " [0.5075],\n", " [0.5564],\n", " [0.5077],\n", " [0.5431],\n", " [0.4493],\n", " [0.6137],\n", " [0.3952]], 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": "c01c9d92", "metadata": {}, "source": [ "## Save torch model" ] }, { "cell_type": "code", "execution_count": 14, "id": "b22b6e10", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T20:25:21.325854Z", "iopub.status.busy": "2026-07-04T20:25:21.325765Z", "iopub.status.idle": "2026-07-04T20:25:21.329091Z", "shell.execute_reply": "2026-07-04T20:25:21.328768Z" } }, "outputs": [], "source": [ "torch.save(model, f\"../weights/{model.metadata['clock_name']}.pt\")" ] }, { "cell_type": "markdown", "id": "e1a96389", "metadata": {}, "source": [ "## Clear directory\n", "" ] }, { "cell_type": "code", "execution_count": 15, "id": "e7b55163", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T20:25:21.330901Z", "iopub.status.busy": "2026-07-04T20:25:21.330792Z", "iopub.status.idle": "2026-07-04T20:25:21.334988Z", "shell.execute_reply": "2026-07-04T20:25:21.334588Z" } }, "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 }