{ "cells": [ { "cell_type": "markdown", "id": "539a5b53", "metadata": {}, "source": [ "# McCartneyAlcohol" ] }, { "cell_type": "markdown", "id": "97fb0a27", "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": "4fd72f26", "metadata": {}, "source": [ "Let's first import some packages:" ] }, { "cell_type": "code", "execution_count": 1, "id": "5ef5fbe0", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:10:41.810213Z", "iopub.status.busy": "2026-07-04T19:10:41.809920Z", "iopub.status.idle": "2026-07-04T19:10:47.260983Z", "shell.execute_reply": "2026-07-04T19:10:47.259455Z" } }, "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": "205370f7", "metadata": {}, "source": [ "## Instantiate model class" ] }, { "cell_type": "code", "execution_count": 2, "id": "f2216aa5", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:10:47.264687Z", "iopub.status.busy": "2026-07-04T19:10:47.264293Z", "iopub.status.idle": "2026-07-04T19:10:47.269795Z", "shell.execute_reply": "2026-07-04T19:10:47.268885Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "class McCartneyAlcohol(pyagingModel):\n", " def __init__(self):\n", " super().__init__()\n", "\n", " def preprocess(self, x):\n", " if self.reference_values is None:\n", " return x\n", " if isinstance(self.reference_values, torch.Tensor):\n", " reference = self.reference_values.to(device=x.device, dtype=x.dtype)\n", " else:\n", " reference = torch.tensor(self.reference_values, device=x.device, dtype=x.dtype)\n", " return torch.where(torch.isnan(x), reference, 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.McCartneyAlcohol)" ] }, { "cell_type": "code", "execution_count": 3, "id": "e66011d2", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:10:47.273368Z", "iopub.status.busy": "2026-07-04T19:10:47.273100Z", "iopub.status.idle": "2026-07-04T19:10:47.277387Z", "shell.execute_reply": "2026-07-04T19:10:47.276165Z" } }, "outputs": [], "source": [ "model = pya.models.McCartneyAlcohol()" ] }, { "cell_type": "markdown", "id": "a21d2c60", "metadata": {}, "source": [ "## Define clock metadata" ] }, { "cell_type": "code", "execution_count": 4, "id": "4f2e25da", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:10:47.280572Z", "iopub.status.busy": "2026-07-04T19:10:47.280332Z", "iopub.status.idle": "2026-07-04T19:10:47.285854Z", "shell.execute_reply": "2026-07-04T19:10:47.284653Z" } }, "outputs": [], "source": [ "model.metadata[\"clock_name\"] = \"mccartneyalcohol\"\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 alcohol consumption, 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\"] = [\"alcohol consumption\"] # Paper: The study developed a DNAm predictor for alcohol consumption.\n", "model.metadata[\"training_target\"] = [\"alcohol consumption\"] # Paper: The alcohol consumption phenotype was regressed on age, sex and ten genetic principal components; its residual was the LASSO outcome.\n", "model.metadata[\"unit\"] = [\"units per week\"] # Paper: No output transformation is applied; the score retains the residual's units-per-week 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\"] = 450\n", "model.metadata[\"citations\"] = 301\n", "model.metadata[\"citations_date\"] = \"2026-07-05\"\n" ] }, { "cell_type": "markdown", "id": "71976082", "metadata": {}, "source": [ "## Download clock dependencies" ] }, { "cell_type": "code", "execution_count": 5, "id": "2daab0ce", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:10:47.289175Z", "iopub.status.busy": "2026-07-04T19:10:47.288861Z", "iopub.status.idle": "2026-07-04T19:10:47.757882Z", "shell.execute_reply": "2026-07-04T19:10:47.756140Z" } }, "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": "3b4aabe3", "metadata": {}, "source": [ "## Load features" ] }, { "cell_type": "code", "execution_count": 6, "id": "94c4d7e5", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:10:47.760782Z", "iopub.status.busy": "2026-07-04T19:10:47.760579Z", "iopub.status.idle": "2026-07-04T19:10:48.007876Z", "shell.execute_reply": "2026-07-04T19:10:48.006978Z" } }, "outputs": [], "source": [ "# Additional file 1, Table S3 - Alcohol (McCartney et al. 2018)\n", "coef_df = pd.read_excel('mccartney_predictors.xlsx', sheet_name='Table S3 - Alcohol')\n", "model.features = coef_df['CpG'].tolist()" ] }, { "cell_type": "markdown", "id": "6e545546", "metadata": {}, "source": [ "## Load weights into base model" ] }, { "cell_type": "code", "execution_count": 7, "id": "2f895ef3", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:10:48.010164Z", "iopub.status.busy": "2026-07-04T19:10:48.009956Z", "iopub.status.idle": "2026-07-04T19:10:48.014051Z", "shell.execute_reply": "2026-07-04T19:10:48.012738Z" } }, "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": "f541eb0d", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:10:48.018314Z", "iopub.status.busy": "2026-07-04T19:10:48.017658Z", "iopub.status.idle": "2026-07-04T19:10:48.023798Z", "shell.execute_reply": "2026-07-04T19:10:48.022961Z" } }, "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": "dfd56006", "metadata": {}, "source": [ "## Load reference values" ] }, { "cell_type": "code", "execution_count": 9, "id": "4aef2faa", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:10:48.026019Z", "iopub.status.busy": "2026-07-04T19:10:48.025839Z", "iopub.status.idle": "2026-07-04T19:10:48.028576Z", "shell.execute_reply": "2026-07-04T19:10:48.027629Z" } }, "outputs": [], "source": [ "model.reference_values = None" ] }, { "cell_type": "markdown", "id": "841edecc", "metadata": {}, "source": [ "## Load preprocess and postprocess objects" ] }, { "cell_type": "code", "execution_count": 10, "id": "a9973413", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:10:48.031380Z", "iopub.status.busy": "2026-07-04T19:10:48.031190Z", "iopub.status.idle": "2026-07-04T19:10:48.034004Z", "shell.execute_reply": "2026-07-04T19:10:48.032843Z" } }, "outputs": [], "source": [ "model.preprocess_name = None\n", "model.preprocess_dependencies = None" ] }, { "cell_type": "code", "execution_count": 11, "id": "ad20d35e", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:10:48.037929Z", "iopub.status.busy": "2026-07-04T19:10:48.037531Z", "iopub.status.idle": "2026-07-04T19:10:48.041406Z", "shell.execute_reply": "2026-07-04T19:10:48.040310Z" } }, "outputs": [], "source": [ "model.postprocess_name = None\n", "model.postprocess_dependencies = None" ] }, { "cell_type": "markdown", "id": "dd897ae9", "metadata": {}, "source": [ "## Check all clock parameters" ] }, { "cell_type": "code", "execution_count": 12, "id": "c9e624da", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:10:48.043707Z", "iopub.status.busy": "2026-07-04T19:10:48.043487Z", "iopub.status.idle": "2026-07-04T19:10:48.051092Z", "shell.execute_reply": "2026-07-04T19:10:48.049872Z" } }, "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': 'mccartneyalcohol',\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: ['cg16113793', 'cg15970375', 'cg16057915', 'cg01503881', 'cg02650017', 'cg08174504', 'cg19613400', 'cg15537269', 'cg08033031', 'cg27078522', 'cg15804767', 'cg27118035', 'cg03440556', 'cg05926784', 'cg24011637', 'cg25215890', 'cg16298547', 'cg05322916', 'cg10785793', 'cg15348839', 'cg20060185', 'cg10747118', 'cg02402946', 'cg00107782', 'cg17301216', 'cg22857025', 'cg27020362', 'cg26516004', 'cg21376883', 'cg13215995']... [Total elements: 450]\n", "base_model_features: None\n", "\n", "%==================================== Model Details ====================================%\n", "Model Structure:\n", "\n", "base_model: LinearModel(\n", " (linear): Linear(in_features=450, out_features=1, bias=True)\n", ")\n", "\n", "%==================================== Model Details ====================================%\n", "Model Parameters and Weights:\n", "\n", "base_model.linear.weight: [3.862548351287842, 2.5282623767852783, 2.1660773754119873, 1.7681397199630737, 1.6551880836486816, 1.3851169347763062, 1.1948226690292358, 1.0830217599868774, 0.9930517077445984, 0.9852260947227478, 0.9295053482055664, 0.9087173342704773, 0.7987855672836304, 0.7958981990814209, 0.7665864825248718, 0.7589118480682373, 0.7468999624252319, 0.6992080807685852, 0.6736985445022583, 0.6460532546043396, 0.6401790380477905, 0.6225373148918152, 0.5754739046096802, 0.5703202486038208, 0.5235690474510193, 0.5012584924697876, 0.4931233823299408, 0.49302104115486145, 0.49224457144737244, 0.48730146884918213]... [Tensor of shape torch.Size([1, 450])]\n", "base_model.linear.bias: tensor([0.])\n", "\n", "%==================================== Model Details ====================================%\n", "\n" ] } ], "source": [ "pya.utils.print_model_details(model)" ] }, { "cell_type": "markdown", "id": "0ac57dcd", "metadata": {}, "source": [ "## Basic test" ] }, { "cell_type": "code", "execution_count": 13, "id": "8c5bd728", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:10:48.054209Z", "iopub.status.busy": "2026-07-04T19:10:48.053838Z", "iopub.status.idle": "2026-07-04T19:10:48.066163Z", "shell.execute_reply": "2026-07-04T19:10:48.065403Z" } }, "outputs": [ { "data": { "text/plain": [ "tensor([[ 2.0260],\n", " [ -7.1355],\n", " [ 13.1317],\n", " [ 23.1027],\n", " [ 8.5896],\n", " [ 17.2480],\n", " [ 7.9061],\n", " [-11.0824],\n", " [ -4.6274],\n", " [ -4.5061]], 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": "93c2ec51", "metadata": {}, "source": [ "## Save torch model" ] }, { "cell_type": "code", "execution_count": 14, "id": "13d0dd7e", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:10:48.070878Z", "iopub.status.busy": "2026-07-04T19:10:48.070541Z", "iopub.status.idle": "2026-07-04T19:10:48.080112Z", "shell.execute_reply": "2026-07-04T19:10:48.078937Z" } }, "outputs": [], "source": [ "torch.save(model, f\"../weights/{model.metadata['clock_name']}.pt\")" ] }, { "cell_type": "markdown", "id": "7d36df3c", "metadata": {}, "source": [ "## Clear directory\n", "" ] }, { "cell_type": "code", "execution_count": 15, "id": "a50b5cf7", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:10:48.084413Z", "iopub.status.busy": "2026-07-04T19:10:48.083927Z", "iopub.status.idle": "2026-07-04T19:10:48.093803Z", "shell.execute_reply": "2026-07-04T19:10:48.092303Z" } }, "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 }