Bohlin#
Index#
Let’s first import some packages:
[1]:
import os
import inspect
import shutil
import json
import torch
import pandas as pd
import pyaging as pya
Instantiate model class#
[2]:
def print_entire_class(cls):
source = inspect.getsource(cls)
print(source)
print_entire_class(pya.models.Bohlin)
class Bohlin(LinearReferenceClock):
def postprocess(self, x):
"""Model returns gestational age in days; convert to weeks."""
return x / 7.0
[3]:
model = pya.models.Bohlin()
Define clock metadata#
[4]:
model.metadata["clock_name"] = "bohlin"
model.metadata["data_type"] = "DNA methylation" # Paper: The predictor uses cord-blood DNA methylation beta values.
model.metadata["species"] = "Homo sapiens" # Paper: The study analyzed newborns from the human MoBa cohort.
model.metadata["year"] = 2016
model.metadata["approved_by_author"] = "⌛"
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)."
model.metadata["doi"] = "https://doi.org/10.1186/s13059-016-1063-4"
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."
model.metadata["research_only"] = None
model.metadata["tissue"] = ["cord blood"] # Paper: Training used Illumina 450K arrays based on newborn cord-blood DNA.
model.metadata["predicts"] = ["gestational age"] # Paper: The model estimates gestational age after birth from cord-blood methylation.
model.metadata["training_target"] = ["gestational age"] # Paper: The primary, better-performing model was trained against ultrasound gestational age.
model.metadata["unit"] = ["weeks"] # Paper: The coefficient formula is in days and the pyaging implementation divides the result by seven.
model.metadata["model_type"] = "LASSO regression" # Paper: Gestational-age prediction used glmnet LASSO regression.
model.metadata["platform"] = ["Illumina 450K"] # Paper: MoBa training methylomes were measured on the Illumina HumanMethylation450 platform.
model.metadata["population"] = "newborns" # Paper: The model was trained in 1,068 MoBa newborns and tested in 685 additional MoBa newborns.
model.metadata["journal"] = "Genome Biology"
model.metadata["last_author"] = "Wenche Nystad"
model.metadata["n_features"] = 251
model.metadata["citations"] = 237
model.metadata["citations_date"] = "2026-07-05"
Download clock dependencies#
[5]:
os.system(f"curl -sL -o coefficients.csv https://raw.githubusercontent.com/Duzhaozhen/OmniAge/c10fbe8cb92957520fbff1d55ae1def0691252e5/OmniAgePy/src/omniage/data/Bohlin_GA.csv")
[5]:
0
Load features#
[6]:
df = pd.read_csv('coefficients.csv')
mask = df['probe'].astype(str).str.lower().isin(['intercept', '(intercept)'])
intercept_value = float(df.loc[mask, 'coef'].iloc[0]) if mask.any() else 0.0
coef_df = df.loc[~mask].reset_index(drop=True)
model.features = coef_df['probe'].tolist()
Load weights into base model#
[7]:
weights = torch.tensor(coef_df['coef'].tolist()).unsqueeze(0).float()
intercept = torch.tensor([intercept_value]).float()
[8]:
base_model = pya.models.LinearModel(input_dim=len(model.features))
base_model.linear.weight.data = weights.float()
base_model.linear.bias.data = intercept.float()
model.base_model = base_model
Load reference values#
[9]:
model.reference_values = None
Load preprocess and postprocess objects#
[10]:
model.preprocess_name = None
model.preprocess_dependencies = None
[11]:
model.postprocess_name = 'days_to_weeks'
model.postprocess_dependencies = None
Check all clock parameters#
[12]:
pya.utils.print_model_details(model)
%==================================== Model Details ====================================%
Model Attributes:
training: True
metadata: {'approved_by_author': '⌛',
'citation': 'Bohlin, Jon, et al. "Prediction of gestational age based on '
'genome-wide differentially methylated regions." Genome Biology '
'17.1 (2016): 207.',
'clock_name': 'bohlin',
'data_type': 'methylation',
'doi': 'https://doi.org/10.1186/s13059-016-1063-4',
'notes': None,
'research_only': None,
'species': 'Homo sapiens',
'version': None,
'year': 2016}
reference_values: None
preprocess_name: None
preprocess_dependencies: None
postprocess_name: 'days_to_weeks'
postprocess_dependencies: None
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]
base_model_features: None
%==================================== Model Details ====================================%
Model Structure:
base_model: LinearModel(
(linear): Linear(in_features=251, out_features=1, bias=True)
)
%==================================== Model Details ====================================%
Model Parameters and Weights:
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])]
base_model.linear.bias: tensor([277.2421])
%==================================== Model Details ====================================%
Basic test#
[13]:
torch.manual_seed(42)
input = torch.randn(10, len(model.features), dtype=float)
model.eval()
model.to(float)
pred = model(input)
pred
[13]:
tensor([[67.3303],
[36.4561],
[18.0902],
[37.1463],
[50.0283],
[48.1619],
[16.2032],
[38.6205],
[60.7712],
[54.3381]], dtype=torch.float64, grad_fn=<DivBackward0>)
Save torch model#
[14]:
torch.save(model, f"../weights/{model.metadata['clock_name']}.pt")
Clear directory#
[15]:
# Function to remove a folder and all its contents
def remove_folder(path):
try:
shutil.rmtree(path)
print(f"Deleted folder: {path}")
except Exception as e:
print(f"Error deleting folder {path}: {e}")
# Get a list of all files and folders in the current directory
all_items = os.listdir('.')
# Loop through the items
for item in all_items:
# Check if it's a file and does not end with .ipynb
if os.path.isfile(item) and not item.endswith('.ipynb'):
os.remove(item)
print(f"Deleted file: {item}")
# Check if it's a folder
elif os.path.isdir(item):
remove_folder(item)
Deleted file: coefficients.csv