{ "cells": [ { "cell_type": "markdown", "id": "717f0170", "metadata": {}, "source": [ "# Bohlin" ] }, { "cell_type": "markdown", "id": "8ef3e665", "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": "c0f66981", "metadata": {}, "source": [ "Let's first import some packages:" ] }, { "cell_type": "code", "execution_count": 1, "id": "9ed8aa30", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T20:25:01.238956Z", "iopub.status.busy": "2026-07-04T20:25:01.238718Z", "iopub.status.idle": "2026-07-04T20:25:03.389470Z", "shell.execute_reply": "2026-07-04T20:25:03.388354Z" } }, "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": "3444bdeb", "metadata": {}, "source": [ "## Instantiate model class" ] }, { "cell_type": "code", "execution_count": 2, "id": "f738e902", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T20:25:03.391420Z", "iopub.status.busy": "2026-07-04T20:25:03.391116Z", "iopub.status.idle": "2026-07-04T20:25:03.394180Z", "shell.execute_reply": "2026-07-04T20:25:03.393837Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "class Bohlin(LinearReferenceClock):\n", " def postprocess(self, x):\n", " \"\"\"Model returns gestational age in days; convert to weeks.\"\"\"\n", " return x / 7.0\n", "\n" ] } ], "source": [ "def print_entire_class(cls):\n", " source = inspect.getsource(cls)\n", " print(source)\n", "\n", "print_entire_class(pya.models.Bohlin)" ] }, { "cell_type": "code", "execution_count": 3, "id": "ec2cc137", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T20:25:03.395464Z", "iopub.status.busy": "2026-07-04T20:25:03.395383Z", "iopub.status.idle": "2026-07-04T20:25:03.397276Z", "shell.execute_reply": "2026-07-04T20:25:03.396806Z" } }, "outputs": [], "source": [ "model = pya.models.Bohlin()" ] }, { "cell_type": "markdown", "id": "ab50c624", "metadata": {}, "source": [ "## Define clock metadata" ] }, { "cell_type": "code", "execution_count": 4, "id": "adac7769", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T20:25:03.398601Z", "iopub.status.busy": "2026-07-04T20:25:03.398503Z", "iopub.status.idle": "2026-07-04T20:25:03.400886Z", "shell.execute_reply": "2026-07-04T20:25:03.400423Z" } }, "outputs": [], "source": [ "model.metadata[\"clock_name\"] = \"bohlin\"\n", "model.metadata[\"data_type\"] = \"DNA methylation\" # Paper: The predictor uses cord-blood DNA methylation beta values.\n", "model.metadata[\"species\"] = \"Homo sapiens\" # Paper: The study analyzed newborns from the human MoBa cohort.\n", "model.metadata[\"year\"] = 2016\n", "model.metadata[\"approved_by_author\"] = \"⌛\"\n", "model.metadata[\"citation\"] = \"Bohlin, J., Håberg, S. E., Magnus, P. et al. Prediction of gestational age based on genome-wide differentially methylated regions. Genome Biology 17, 207 (2016).\"\n", "model.metadata[\"doi\"] = \"https://doi.org/10.1186/s13059-016-1063-4\"\n", "model.metadata[\"notes\"] = \"Official minimum-lambda variant of the Bohlin gestational-age LASSO: pyaging implements the 251-CpG lambda.min model and converts its day-scale output to weeks. The paper/package default one-standard-error variant uses 96 CpGs and has nearly identical predictive performance.\"\n", "model.metadata[\"research_only\"] = None\n", "model.metadata[\"tissue\"] = [\"cord blood\"] # Paper: Training used Illumina 450K arrays based on newborn cord-blood DNA.\n", "model.metadata[\"predicts\"] = [\"gestational age\"] # Paper: The model estimates gestational age after birth from cord-blood methylation.\n", "model.metadata[\"training_target\"] = [\"gestational age\"] # Paper: The primary, better-performing model was trained against ultrasound gestational age.\n", "model.metadata[\"unit\"] = [\"weeks\"] # Paper: The coefficient formula is in days and the pyaging implementation divides the result by seven.\n", "model.metadata[\"model_type\"] = \"LASSO regression\" # Paper: Gestational-age prediction used glmnet LASSO regression.\n", "model.metadata[\"platform\"] = [\"Illumina 450K\"] # Paper: MoBa training methylomes were measured on the Illumina HumanMethylation450 platform.\n", "model.metadata[\"population\"] = \"newborns\" # Paper: The model was trained in 1,068 MoBa newborns and tested in 685 additional MoBa newborns.\n", "model.metadata[\"journal\"] = \"Genome Biology\"\n", "model.metadata[\"last_author\"] = \"Wenche Nystad\"\n", "model.metadata[\"n_features\"] = 251\n", "model.metadata[\"citations\"] = 237\n", "model.metadata[\"citations_date\"] = \"2026-07-05\"\n" ] }, { "cell_type": "markdown", "id": "830c4189", "metadata": {}, "source": [ "## Download clock dependencies" ] }, { "cell_type": "code", "execution_count": 5, "id": "291f98b7", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T20:25:03.402146Z", "iopub.status.busy": "2026-07-04T20:25:03.402068Z", "iopub.status.idle": "2026-07-04T20:25:03.684827Z", "shell.execute_reply": "2026-07-04T20:25:03.683624Z" } }, "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/Duzhaozhen/OmniAge/c10fbe8cb92957520fbff1d55ae1def0691252e5/OmniAgePy/src/omniage/data/Bohlin_GA.csv\")" ] }, { "cell_type": "markdown", "id": "19851305", "metadata": {}, "source": [ "## Load features" ] }, { "cell_type": "code", "execution_count": 6, "id": "70b59676", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T20:25:03.688299Z", "iopub.status.busy": "2026-07-04T20:25:03.688026Z", "iopub.status.idle": "2026-07-04T20:25:03.697422Z", "shell.execute_reply": "2026-07-04T20:25:03.696744Z" } }, "outputs": [], "source": [ "df = pd.read_csv('coefficients.csv')\n", "mask = df['probe'].astype(str).str.lower().isin(['intercept', '(intercept)'])\n", "intercept_value = float(df.loc[mask, 'coef'].iloc[0]) if mask.any() else 0.0\n", "coef_df = df.loc[~mask].reset_index(drop=True)\n", "model.features = coef_df['probe'].tolist()" ] }, { "cell_type": "markdown", "id": "117da281", "metadata": {}, "source": [ "## Load weights into base model" ] }, { "cell_type": "code", "execution_count": 7, "id": "ef29494e", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T20:25:03.699299Z", "iopub.status.busy": "2026-07-04T20:25:03.699146Z", "iopub.status.idle": "2026-07-04T20:25:03.701747Z", "shell.execute_reply": "2026-07-04T20:25:03.701259Z" } }, "outputs": [], "source": [ "weights = torch.tensor(coef_df['coef'].tolist()).unsqueeze(0).float()\n", "intercept = torch.tensor([intercept_value]).float()" ] }, { "cell_type": "code", "execution_count": 8, "id": "39896fe7", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T20:25:03.703008Z", "iopub.status.busy": "2026-07-04T20:25:03.702920Z", "iopub.status.idle": "2026-07-04T20:25:03.704983Z", "shell.execute_reply": "2026-07-04T20:25:03.704640Z" } }, "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": "1bededf4", "metadata": {}, "source": [ "## Load reference values" ] }, { "cell_type": "code", "execution_count": 9, "id": "27476e4e", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T20:25:03.706270Z", "iopub.status.busy": "2026-07-04T20:25:03.706195Z", "iopub.status.idle": "2026-07-04T20:25:03.707735Z", "shell.execute_reply": "2026-07-04T20:25:03.707342Z" } }, "outputs": [], "source": [ "model.reference_values = None" ] }, { "cell_type": "markdown", "id": "2bc67e24", "metadata": {}, "source": [ "## Load preprocess and postprocess objects" ] }, { "cell_type": "code", "execution_count": 10, "id": "a967bfac", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T20:25:03.708890Z", "iopub.status.busy": "2026-07-04T20:25:03.708821Z", "iopub.status.idle": "2026-07-04T20:25:03.710357Z", "shell.execute_reply": "2026-07-04T20:25:03.710035Z" } }, "outputs": [], "source": [ "model.preprocess_name = None\n", "model.preprocess_dependencies = None" ] }, { "cell_type": "code", "execution_count": 11, "id": "466c93e6", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T20:25:03.711475Z", "iopub.status.busy": "2026-07-04T20:25:03.711405Z", "iopub.status.idle": "2026-07-04T20:25:03.713066Z", "shell.execute_reply": "2026-07-04T20:25:03.712607Z" } }, "outputs": [], "source": [ "model.postprocess_name = 'days_to_weeks'\n", "model.postprocess_dependencies = None" ] }, { "cell_type": "markdown", "id": "fce69e38", "metadata": {}, "source": [ "## Check all clock parameters" ] }, { "cell_type": "code", "execution_count": 12, "id": "166a9e08", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T20:25:03.714484Z", "iopub.status.busy": "2026-07-04T20:25:03.714389Z", "iopub.status.idle": "2026-07-04T20:25:03.719171Z", "shell.execute_reply": "2026-07-04T20:25:03.718310Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "%==================================== Model Details ====================================%\n", "Model Attributes:\n", "\n", "training: True\n", "metadata: {'approved_by_author': '⌛',\n", " 'citation': 'Bohlin, Jon, et al. \"Prediction of gestational age based on '\n", " 'genome-wide differentially methylated regions.\" Genome Biology '\n", " '17.1 (2016): 207.',\n", " 'clock_name': 'bohlin',\n", " 'data_type': 'methylation',\n", " 'doi': 'https://doi.org/10.1186/s13059-016-1063-4',\n", " 'notes': None,\n", " 'research_only': None,\n", " 'species': 'Homo sapiens',\n", " 'version': None,\n", " 'year': 2016}\n", "reference_values: None\n", "preprocess_name: None\n", "preprocess_dependencies: None\n", "postprocess_name: 'days_to_weeks'\n", "postprocess_dependencies: None\n", "features: ['cg00099441', 'cg00117869', 'cg00303541', 'cg00602416', 'cg00711496', 'cg00898111', 'cg01091356', 'cg01139861', 'cg01190109', 'cg01281797', 'cg01359999', 'cg01382072', 'cg01470456', 'cg01505275', 'cg01635555', 'cg01697487', 'cg01749742', 'cg01833485', 'cg01847441', 'cg02324006', 'cg02358664', 'cg02378208', 'cg02405476', 'cg02567958', 'cg02576394', 'cg02642822', 'cg02779037', 'cg02853322', 'cg02985694', 'cg03098721']... [Total elements: 251]\n", "base_model_features: None\n", "\n", "%==================================== Model Details ====================================%\n", "Model Structure:\n", "\n", "base_model: LinearModel(\n", " (linear): Linear(in_features=251, out_features=1, bias=True)\n", ")\n", "\n", "%==================================== Model Details ====================================%\n", "Model Parameters and Weights:\n", "\n", "base_model.linear.weight: [1.679152488708496, -2.247448444366455, -8.844316482543945, 3.3127026557922363, -1.2231009006500244, 0.2817184627056122, 0.6226192712783813, 1.777445673942566, 9.944578170776367, 25.59168243408203, 4.947725772857666, 3.4168262481689453, -0.4994896650314331, -2.2033567428588867, 5.669358730316162, 1.2348579168319702, 0.014705928973853588, 3.155426263809204, 2.1350390911102295, -12.360982894897461, 1.5933818817138672, -2.458742618560791, 11.212024688720703, -16.415714263916016, -4.602630138397217, -3.348295211791992, -2.3952744007110596, 7.600930213928223, -4.37376594543457, 8.569387435913086]... [Tensor of shape torch.Size([1, 251])]\n", "base_model.linear.bias: tensor([277.2421])\n", "\n", "%==================================== Model Details ====================================%\n", "\n" ] } ], "source": [ "pya.utils.print_model_details(model)" ] }, { "cell_type": "markdown", "id": "1d5ab505", "metadata": {}, "source": [ "## Basic test" ] }, { "cell_type": "code", "execution_count": 13, "id": "259e4b13", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T20:25:03.722114Z", "iopub.status.busy": "2026-07-04T20:25:03.721981Z", "iopub.status.idle": "2026-07-04T20:25:03.726325Z", "shell.execute_reply": "2026-07-04T20:25:03.725928Z" } }, "outputs": [ { "data": { "text/plain": [ "tensor([[67.3303],\n", " [36.4561],\n", " [18.0902],\n", " [37.1463],\n", " [50.0283],\n", " [48.1619],\n", " [16.2032],\n", " [38.6205],\n", " [60.7712],\n", " [54.3381]], 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": "aee7f34f", "metadata": {}, "source": [ "## Save torch model" ] }, { "cell_type": "code", "execution_count": 14, "id": "64ca20a7", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T20:25:03.727644Z", "iopub.status.busy": "2026-07-04T20:25:03.727567Z", "iopub.status.idle": "2026-07-04T20:25:03.731485Z", "shell.execute_reply": "2026-07-04T20:25:03.730983Z" } }, "outputs": [], "source": [ "torch.save(model, f\"../weights/{model.metadata['clock_name']}.pt\")" ] }, { "cell_type": "markdown", "id": "695ec299", "metadata": {}, "source": [ "## Clear directory\n", "" ] }, { "cell_type": "code", "execution_count": 15, "id": "c50bcfdf", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T20:25:03.733306Z", "iopub.status.busy": "2026-07-04T20:25:03.733156Z", "iopub.status.idle": "2026-07-04T20:25:03.737057Z", "shell.execute_reply": "2026-07-04T20:25:03.736668Z" } }, "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 }