VidalBralo#

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.VidalBralo)
class VidalBralo(pyagingModel):
    def __init__(self):
        super().__init__()

    def preprocess(self, x):
        if self.reference_values is None:
            return x
        if isinstance(self.reference_values, torch.Tensor):
            reference = self.reference_values.to(device=x.device, dtype=x.dtype)
        else:
            reference = torch.tensor(self.reference_values, device=x.device, dtype=x.dtype)
        return torch.where(torch.isnan(x), reference, x)

    def postprocess(self, x):
        return x

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

Define clock metadata#

[4]:
model.metadata["clock_name"] = 'vidalbralo'
model.metadata["data_type"] = 'methylation'
model.metadata["species"] = 'Homo sapiens'
model.metadata["year"] = 2016
model.metadata["approved_by_author"] = '⌛'
model.metadata["citation"] = "Vidal-Bralo, Laura, Yolanda Lopez-Golan, and Antonio Gonzalez. \"Simplified assay for epigenetic age estimation in whole blood of adults.\" Frontiers in genetics 7 (2016): 126."
model.metadata["doi"] = "https://doi.org/10.3389/fgene.2016.00126"
model.metadata["research_only"] = None
model.metadata["notes"] = "Whole-blood epigenetic age estimator for adults built by stepwise multiple linear regression over eight CpG sites, designed to run as a single low-cost MS-SNuPE multiplex assay rather than a genome-wide methylation microarray."
model.metadata["tissue"] = 'whole blood'
model.metadata["predicts"] = 'chronological age'
model.metadata["unit"] = 'years'
model.metadata["model_type"] = 'Bayesian regression'
model.metadata["platform"] = 'Illumina 27K/450K'
model.metadata["population"] = 'adults (>20 years)'
model.metadata["journal"] = 'Frontiers in Genetics'
model.metadata["last_author"] = 'Antonio González'
model.metadata["n_features"] = 8
model.metadata["citations"] = 145
model.metadata["citations_date"] = '2026-07-05'

Download clock dependencies#

[5]:
# The 8-CpG DmAM coefficients are given directly in Table 2 of
# Vidal-Bralo et al. 2016 (Front. Genet. 7:126); they are defined inline below,
# so no external download is required.

Load features#

[6]:
# Multiple linear regression parameters of the 8 CpG DmAM (Vidal-Bralo et al. 2016, Table 2)
coef_df = pd.DataFrame({
    'CpG': ['cg16386080', 'cg24768561', 'cg19761273', 'cg25809905',
            'cg09809672', 'cg02228185', 'cg17471102', 'cg10917602'],
    'coefficient': [59.5, 33.9, -44.0, -19.7, -22.8, -16.8, -17.7, -11.4],
})
model.features = coef_df['CpG'].tolist()

Load weights into base model#

[7]:
weights = torch.tensor(coef_df['coefficient'].tolist()).unsqueeze(0).float()
intercept = torch.tensor([84.7]).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': 'Vidal-Bralo, Laura, Yolanda Lopez-Golan, and Antonio Gonzalez. '
             '"Simplified assay for epigenetic age estimation in whole blood '
             'of adults." Frontiers in genetics 7 (2016): 126.',
 'clock_name': 'vidalbralo',
 'data_type': 'methylation',
 'doi': 'https://doi.org/10.3389/fgene.2016.00126',
 'notes': None,
 'research_only': None,
 'species': 'Homo sapiens',
 'version': None,
 'year': 2016}
reference_values: None
preprocess_name: None
preprocess_dependencies: None
postprocess_name: None
postprocess_dependencies: None
features: ['cg16386080',
 'cg24768561',
 'cg19761273',
 'cg25809905',
 'cg09809672',
 'cg02228185',
 'cg17471102',
 'cg10917602']
base_model_features: None

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

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

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

base_model.linear.weight: tensor([[ 59.5000,  33.9000, -44.0000, -19.7000, -22.8000, -16.8000, -17.7000,
         -11.4000]])
base_model.linear.bias: tensor([84.7000])

%==================================== 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([[126.0523],
        [104.1466],
        [ 75.2432],
        [ 58.5473],
        [160.9427],
        [ 27.2660],
        [137.7398],
        [262.1763],
        [125.6747],
        [171.3440]], 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)