ReedBMI#

Index#

  1. Instantiate model class

  2. Define clock metadata

  3. Download clock dependencies

  4. Load features

  5. Load weights into base model

  6. Load reference values

  7. Load preprocess and postprocess objects

  8. Check all clock parameters

  9. Basic test

  10. Save torch model

  11. Clear directory

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.ReedBMI)
class ReedBMI(LinearReferenceClock):
    pass

[3]:
model = pya.models.ReedBMI()

Define clock metadata#

[4]:
model.metadata["clock_name"] = 'reedbmi'
model.metadata["data_type"] = 'methylation'
model.metadata["species"] = 'Homo sapiens'
model.metadata["year"] = 2020
model.metadata["approved_by_author"] = '⌛'
model.metadata["citation"] = "Reed, Zoe E., et al. \"Perinatal and childhood epigenetic biomarkers of body composition.\" Clinical Epigenetics 12.1 (2020): 156."
model.metadata["doi"] = "https://doi.org/10.1186/s13148-020-00841-5"
model.metadata["research_only"] = None
model.metadata["notes"] = "Blood DNA-methylation score for body mass index, computed as a weighted combination of CpGs drawn from published BMI epigenome-wide associations. It was evaluated across the life course from birth through adulthood in a longitudinal mother-child cohort to separate methylation that acts as a biomarker of current BMI from methylation that predicts future BMI."
model.metadata["tissue"] = 'whole blood (peripheral blood; umbilical cord blood at birth)'
model.metadata["predicts"] = 'body mass index (BMI) - biomarker of extant/concurrent BMI'
model.metadata["unit"] = 'kilograms'
model.metadata["model_type"] = 'Weighted average of CpGs'
model.metadata["platform"] = 'Illumina 450K'
model.metadata["population"] = 'pan-age (birth, childhood ~7y, adolescence ~15-17y, pregnancy ~29y, middle age ~48y); ARIES/ALSPAC mother-child cohort'
model.metadata["journal"] = 'Clinical Epigenetics'
model.metadata["last_author"] = 'Gibran Hemani'
model.metadata["n_features"] = 135
model.metadata["citations"] = 86
model.metadata["citations_date"] = '2026-07-05'

Download clock dependencies#

[5]:
os.system(f"curl -sL -o coefficients.csv https://raw.githubusercontent.com/bio-learn/biolearn/180852e2bab473303cb85da627178b1695ee9d86/biolearn/data/BMI_Reed.csv")
[5]:
0

Load features#

[6]:
df = pd.read_csv('coefficients.csv')
mask = df['CpGmarker'].astype(str).str.lower().isin(['intercept', '(intercept)'])
intercept_value = float(df.loc[mask, 'CoefficientTraining'].iloc[0]) if mask.any() else 0.0
coef_df = df.loc[~mask].reset_index(drop=True)
model.features = coef_df['CpGmarker'].tolist()

Load weights into base model#

[7]:
weights = torch.tensor(coef_df['CoefficientTraining'].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 = None
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': 'Reed, Zoe E., et al. "Perinatal and childhood epigenetic '
             'biomarkers of body composition." Clinical Epigenetics 12.1 '
             '(2020): 156.',
 'clock_name': 'reedbmi',
 'data_type': 'methylation',
 'doi': 'https://doi.org/10.1186/s13148-020-00841-5',
 'notes': None,
 'research_only': None,
 'species': 'Homo sapiens',
 'version': None,
 'year': 2020}
reference_values: None
preprocess_name: None
preprocess_dependencies: None
postprocess_name: None
postprocess_dependencies: None
features: ['cg00108715', 'cg00222799', 'cg00574958', 'cg01130991', 'cg01243823', 'cg01368219', 'cg01455178', 'cg01526748', 'cg01597398', 'cg01671681', 'cg01751802', 'cg01798813', 'cg01881899', 'cg02286155', 'cg02571142', 'cg02711608', 'cg02716826', 'cg03078551', 'cg03218374', 'cg03500056', 'cg03682690', 'cg03725309', 'cg04011474', 'cg04286697', 'cg04483863', 'cg04557677', 'cg04816311', 'cg04927537', 'cg05119988', 'cg06192883']... [Total elements: 135]
base_model_features: None

%==================================== Model Details ====================================%
Model Structure:

base_model: LinearModel(
  (linear): Linear(in_features=135, out_features=1, bias=True)
)

%==================================== Model Details ====================================%
Model Parameters and Weights:

base_model.linear.weight: [0.007000000216066837, 0.007000000216066837, -0.019999999552965164, 0.009999999776482582, -0.00800000037997961, 0.00800000037997961, 0.008999999612569809, 0.008999999612569809, -0.006000000052154064, -0.00800000037997961, 0.00800000037997961, 0.009999999776482582, 0.009999999776482582, 0.006000000052154064, 0.00800000037997961, -0.00800000037997961, -0.00800000037997961, -0.009999999776482582, 0.008999999612569809, 0.006000000052154064, 0.009999999776482582, -0.009999999776482582, -0.00800000037997961, 0.007000000216066837, 0.008999999612569809, -0.00800000037997961, 0.009999999776482582, 0.009999999776482582, -0.008999999612569809, 0.00800000037997961]... [Tensor of shape torch.Size([1, 135])]
base_model.linear.bias: tensor([0.])

%==================================== 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([[ 0.1953],
        [-0.0139],
        [ 0.0094],
        [-0.0168],
        [ 0.0056],
        [ 0.0452],
        [ 0.0059],
        [ 0.0187],
        [ 0.1456],
        [-0.0608]], dtype=torch.float64, grad_fn=<AddmmBackward0>)

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