{ "cells": [ { "cell_type": "markdown", "id": "8dcf2da8", "metadata": {}, "source": [ "# McCartneyTotalHDLRatio" ] }, { "cell_type": "markdown", "id": "b059f182", "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": "1aa2a0ab", "metadata": {}, "source": [ "Let's first import some packages:" ] }, { "cell_type": "code", "execution_count": 1, "id": "bdc0586b", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:26:28.608178Z", "iopub.status.busy": "2026-07-04T19:26:28.606958Z", "iopub.status.idle": "2026-07-04T19:26:32.797901Z", "shell.execute_reply": "2026-07-04T19:26:32.797421Z" } }, "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": "75674269", "metadata": {}, "source": [ "## Instantiate model class" ] }, { "cell_type": "code", "execution_count": 2, "id": "3324948f", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:26:32.799674Z", "iopub.status.busy": "2026-07-04T19:26:32.799433Z", "iopub.status.idle": "2026-07-04T19:26:32.803129Z", "shell.execute_reply": "2026-07-04T19:26:32.802662Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "class McCartneyTotalHDLRatio(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.McCartneyTotalHDLRatio)" ] }, { "cell_type": "code", "execution_count": 3, "id": "cd056339", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:26:32.804708Z", "iopub.status.busy": "2026-07-04T19:26:32.804603Z", "iopub.status.idle": "2026-07-04T19:26:32.806539Z", "shell.execute_reply": "2026-07-04T19:26:32.806089Z" } }, "outputs": [], "source": [ "model = pya.models.McCartneyTotalHDLRatio()" ] }, { "cell_type": "markdown", "id": "6b5f9857", "metadata": {}, "source": [ "## Define clock metadata" ] }, { "cell_type": "code", "execution_count": 4, "id": "612ed553", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:26:32.807855Z", "iopub.status.busy": "2026-07-04T19:26:32.807763Z", "iopub.status.idle": "2026-07-04T19:26:32.809884Z", "shell.execute_reply": "2026-07-04T19:26:32.809443Z" } }, "outputs": [], "source": [ "model.metadata[\"clock_name\"] = \"mccartneytotalhdlratio\"\n", "model.metadata[\"data_type\"] = \"DNA methylation\" # Paper: The predictors use DNA methylation states at CpG sites.\n", "model.metadata[\"species\"] = \"Homo sapiens\" # Paper: Generation Scotland is a population-based cohort of human participants.\n", "model.metadata[\"year\"] = 2018\n", "model.metadata[\"approved_by_author\"] = \"⌛\"\n", "model.metadata[\"citation\"] = \"McCartney, D. L., et al. “Epigenetic prediction of complex traits and death.” Genome Biology 19, 136 (2018).\"\n", "model.metadata[\"doi\"] = \"https://doi.org/10.1186/s13059-018-1514-1\"\n", "model.metadata[\"notes\"] = \"Whole-blood DNAm LASSO score for total-to-HDL cholesterol ratio, trained in Generation Scotland on an age-, sex-, and ancestry-adjusted phenotype residual and evaluated out of sample in LBC1936.\"\n", "model.metadata[\"research_only\"] = None\n", "model.metadata[\"tissue\"] = [\"whole blood\"] # Paper: Stored DNA from baseline blood samples was used to build the predictors.\n", "model.metadata[\"predicts\"] = [\"total-to-HDL cholesterol ratio\"] # Paper: The study developed a DNAm predictor for total-to-HDL cholesterol ratio.\n", "model.metadata[\"training_target\"] = [\"total-to-HDL cholesterol ratio\"] # Paper: The total-to-HDL cholesterol ratio phenotype was regressed on age, sex and ten genetic principal components; its residual was the LASSO outcome.\n", "model.metadata[\"unit\"] = [\"ratio\"] # Paper: No output transformation is applied; the score retains the dimensionless ratio-residual scale.\n", "model.metadata[\"model_type\"] = \"LASSO regression\" # Paper: The glmnet mixing parameter alpha was set to 1, applying a LASSO penalty with tenfold cross-validation.\n", "model.metadata[\"platform\"] = [\"Illumina EPIC\"] # Paper: Predictor training used quality-controlled HumanMethylationEPIC blood data; probes absent from 450K were filtered only to enable LBC1936 prediction.\n", "model.metadata[\"population\"] = \"adults\" # Paper: The predictors were built on a subset of 5,087 Generation Scotland participants; the parent cohort spans ages 18–99.\n", "model.metadata[\"journal\"] = \"Genome Biology\"\n", "model.metadata[\"last_author\"] = \"Riccardo E. Marioni\"\n", "model.metadata[\"n_features\"] = 412\n", "model.metadata[\"citations\"] = 301\n", "model.metadata[\"citations_date\"] = \"2026-07-05\"\n" ] }, { "cell_type": "markdown", "id": "de9c3f78", "metadata": {}, "source": [ "## Download clock dependencies" ] }, { "cell_type": "code", "execution_count": 5, "id": "d89cefe9", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:26:32.811481Z", "iopub.status.busy": "2026-07-04T19:26:32.811363Z", "iopub.status.idle": "2026-07-04T19:26:33.204157Z", "shell.execute_reply": "2026-07-04T19:26:33.203601Z" } }, "outputs": [ { "data": { "text/plain": [ "0" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "supplementary_url = \"https://static-content.springer.com/esm/art%3A10.1186%2Fs13059-018-1514-1/MediaObjects/13059_2018_1514_MOESM1_ESM.xlsx\"\n", "supplementary_file_name = \"mccartney_predictors.xlsx\"\n", "os.system(f\"curl -sL -o {supplementary_file_name} {supplementary_url}\")" ] }, { "cell_type": "markdown", "id": "ce3afcd3", "metadata": {}, "source": [ "## Load features" ] }, { "cell_type": "code", "execution_count": 6, "id": "d788f48b", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:26:33.205371Z", "iopub.status.busy": "2026-07-04T19:26:33.205281Z", "iopub.status.idle": "2026-07-04T19:26:33.361405Z", "shell.execute_reply": "2026-07-04T19:26:33.360808Z" } }, "outputs": [], "source": [ "# Additional file 1, Table S8 - Total-HDL ratio (McCartney et al. 2018)\n", "coef_df = pd.read_excel('mccartney_predictors.xlsx', sheet_name='Table S8 - Total-HDL ratio')\n", "model.features = coef_df['CpG'].tolist()" ] }, { "cell_type": "markdown", "id": "ea408b14", "metadata": {}, "source": [ "## Load weights into base model" ] }, { "cell_type": "code", "execution_count": 7, "id": "c1cbe9ab", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:26:33.362813Z", "iopub.status.busy": "2026-07-04T19:26:33.362723Z", "iopub.status.idle": "2026-07-04T19:26:33.369802Z", "shell.execute_reply": "2026-07-04T19:26:33.369239Z" } }, "outputs": [], "source": [ "# The penalised (LASSO) predictor has no intercept term\n", "weights = torch.tensor(coef_df['Beta'].tolist()).unsqueeze(0).float()\n", "intercept = torch.tensor([0.0]).float()" ] }, { "cell_type": "code", "execution_count": 8, "id": "ea706b57", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:26:33.371358Z", "iopub.status.busy": "2026-07-04T19:26:33.371247Z", "iopub.status.idle": "2026-07-04T19:26:33.376618Z", "shell.execute_reply": "2026-07-04T19:26:33.376125Z" } }, "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": "f49e5648", "metadata": {}, "source": [ "## Load reference values" ] }, { "cell_type": "code", "execution_count": 9, "id": "203cd580", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:26:33.378204Z", "iopub.status.busy": "2026-07-04T19:26:33.378097Z", "iopub.status.idle": "2026-07-04T19:26:33.380049Z", "shell.execute_reply": "2026-07-04T19:26:33.379619Z" } }, "outputs": [], "source": [ "model.reference_values = None" ] }, { "cell_type": "markdown", "id": "274e41de", "metadata": {}, "source": [ "## Load preprocess and postprocess objects" ] }, { "cell_type": "code", "execution_count": 10, "id": "2dfdd2fd", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:26:33.382363Z", "iopub.status.busy": "2026-07-04T19:26:33.382222Z", "iopub.status.idle": "2026-07-04T19:26:33.383938Z", "shell.execute_reply": "2026-07-04T19:26:33.383519Z" } }, "outputs": [], "source": [ "model.preprocess_name = None\n", "model.preprocess_dependencies = None" ] }, { "cell_type": "code", "execution_count": 11, "id": "50d76ad9", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:26:33.385087Z", "iopub.status.busy": "2026-07-04T19:26:33.385013Z", "iopub.status.idle": "2026-07-04T19:26:33.386987Z", "shell.execute_reply": "2026-07-04T19:26:33.386505Z" } }, "outputs": [], "source": [ "model.postprocess_name = None\n", "model.postprocess_dependencies = None" ] }, { "cell_type": "markdown", "id": "c140f14c", "metadata": {}, "source": [ "## Check all clock parameters" ] }, { "cell_type": "code", "execution_count": 12, "id": "513c1a26", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:26:33.388289Z", "iopub.status.busy": "2026-07-04T19:26:33.388209Z", "iopub.status.idle": "2026-07-04T19:26:33.403317Z", "shell.execute_reply": "2026-07-04T19:26:33.402926Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "%==================================== Model Details ====================================%\n", "Model Attributes:\n", "\n", "training: True\n", "metadata: {'approved_by_author': '⌛',\n", " 'citation': 'McCartney, Daniel L., et al. \"Epigenetic prediction of complex '\n", " 'traits and death.\" Genome biology 19.1 (2018): 136.',\n", " 'clock_name': 'mccartneytotalhdlratio',\n", " 'data_type': 'methylation',\n", " 'doi': 'https://doi.org/10.1186/s13059-018-1514-1',\n", " 'notes': None,\n", " 'research_only': None,\n", " 'species': 'Homo sapiens',\n", " 'version': None,\n", " 'year': 2018}\n", "reference_values: None\n", "preprocess_name: None\n", "preprocess_dependencies: None\n", "postprocess_name: None\n", "postprocess_dependencies: None\n", "features: ['cg24576270', 'cg25158622', 'cg06500161', 'cg26033520', 'cg18615457', 'cg10993470', 'cg19250790', 'cg09177238', 'cg22813794', 'cg01511534', 'cg01559436', 'cg22488164', 'cg05391946', 'cg09503194', 'cg14697880', 'cg06136443', 'cg14545305', 'cg26955383', 'cg26800462', 'cg08854185', 'cg14891022', 'cg23719318', 'cg12332083', 'cg02150767', 'cg08864105', 'cg11770080', 'cg12422930', 'cg06898549', 'cg03546163', 'cg26245667']... [Total elements: 412]\n", "base_model_features: None\n", "\n", "%==================================== Model Details ====================================%\n", "Model Structure:\n", "\n", "base_model: LinearModel(\n", " (linear): Linear(in_features=412, out_features=1, bias=True)\n", ")\n", "\n", "%==================================== Model Details ====================================%\n", "Model Parameters and Weights:\n", "\n", "base_model.linear.weight: [16.199861526489258, 1.5791822671890259, 1.3397550582885742, 1.2062699794769287, 1.1696120500564575, 1.1656070947647095, 1.0623283386230469, 0.9755944609642029, 0.9740409851074219, 0.9441574811935425, 0.8715856671333313, 0.8420827984809875, 0.8233152627944946, 0.8100341558456421, 0.7970923781394958, 0.7889676690101624, 0.7783008217811584, 0.7704609632492065, 0.7500393986701965, 0.7299103736877441, 0.7206714153289795, 0.6958703994750977, 0.6573514342308044, 0.6428144574165344, 0.637154221534729, 0.6069923043251038, 0.600265383720398, 0.5983773469924927, 0.5772433876991272, 0.5692275166511536]... [Tensor of shape torch.Size([1, 412])]\n", "base_model.linear.bias: tensor([0.])\n", "\n", "%==================================== Model Details ====================================%\n", "\n" ] } ], "source": [ "pya.utils.print_model_details(model)" ] }, { "cell_type": "markdown", "id": "5897924e", "metadata": {}, "source": [ "## Basic test" ] }, { "cell_type": "code", "execution_count": 13, "id": "2676cde5", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:26:33.404694Z", "iopub.status.busy": "2026-07-04T19:26:33.404602Z", "iopub.status.idle": "2026-07-04T19:26:33.422273Z", "shell.execute_reply": "2026-07-04T19:26:33.421879Z" } }, "outputs": [ { "data": { "text/plain": [ "tensor([[ 17.9949],\n", " [ -3.0065],\n", " [-38.9142],\n", " [ 1.3466],\n", " [ 9.2999],\n", " [ 5.4597],\n", " [ 14.3734],\n", " [ -9.2779],\n", " [ -9.3156],\n", " [-27.2043]], 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": "96600ffc", "metadata": {}, "source": [ "## Save torch model" ] }, { "cell_type": "code", "execution_count": 14, "id": "cfbede23", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:26:33.423648Z", "iopub.status.busy": "2026-07-04T19:26:33.423558Z", "iopub.status.idle": "2026-07-04T19:26:33.428839Z", "shell.execute_reply": "2026-07-04T19:26:33.428242Z" } }, "outputs": [], "source": [ "torch.save(model, f\"../weights/{model.metadata['clock_name']}.pt\")" ] }, { "cell_type": "markdown", "id": "5764882c", "metadata": {}, "source": [ "## Clear directory\n", "" ] }, { "cell_type": "code", "execution_count": 15, "id": "3c1cb37b", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:26:33.430461Z", "iopub.status.busy": "2026-07-04T19:26:33.430314Z", "iopub.status.idle": "2026-07-04T19:26:33.434239Z", "shell.execute_reply": "2026-07-04T19:26:33.433753Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Deleted file: mccartney_predictors.xlsx\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 }