ABEC#

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

    def preprocess(self, x):
        return x

    def postprocess(self, x):
        return x

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

Define clock metadata#

[4]:
model.metadata["clock_name"] = 'abec'
model.metadata["data_type"] = 'methylation'
model.metadata["species"] = 'Homo sapiens'
model.metadata["year"] = 2020
model.metadata["approved_by_author"] = '⌛'
model.metadata["citation"] = "Lee, Yunsung, et al. \"Blood-based epigenetic estimators of chronological age in human adults using DNA methylation data from the Illumina MethylationEPIC array.\" BMC genomics 21 (2020): 1-13."
model.metadata["doi"] = "https://doi.org/10.1186/s12864-020-07168-8"
model.metadata["research_only"] = None
model.metadata["notes"] = "Whole-blood elastic-net clock (the Adult Blood-based EPIC Clock) that estimates chronological age from Illumina MethylationEPIC-array CpGs, trained on adult peripheral-blood DNA methylation spanning roughly two to six decades of age."
model.metadata["tissue"] = 'whole blood'
model.metadata["predicts"] = 'chronological age'
model.metadata["unit"] = 'years'
model.metadata["model_type"] = 'Elastic net'
model.metadata["platform"] = 'Illumina EPIC'
model.metadata["population"] = 'adults, 19-59 years (ABEC training set; related eABEC/cABEC clocks span 18-88 years)'
model.metadata["journal"] = 'BMC Genomics'
model.metadata["last_author"] = 'Jon Bohlin'
model.metadata["n_features"] = 1695
model.metadata["citations"] = 21
model.metadata["citations_date"] = '2026-07-05'

Download clock dependencies#

Download directly with curl#

[5]:
supplementary_url = "https://static-content.springer.com/esm/art%3A10.1186%2Fs12864-020-07168-8/MediaObjects/12864_2020_7168_MOESM1_ESM.csv"
supplementary_file_name = "coefficients.csv"
os.system(f"curl -o {supplementary_file_name} {supplementary_url}")
[5]:
0

Load features#

From CSV file#

[6]:
df = pd.read_csv('coefficients.csv', index_col=0)
df = df[~df['ABEC_coefficient'].isna()]
df['feature'] = df.index.tolist()
df['coefficient'] = df['ABEC_coefficient']
model.features = df['feature'][1:].tolist()

Load weights into base model#

[7]:
weights = torch.tensor(df['coefficient'][1:].tolist()).unsqueeze(0)
intercept = torch.tensor([df['coefficient'][0]])
<ipython-input-7-232b7c74dbf3>:2: FutureWarning: Series.__getitem__ treating keys as positions is deprecated. In a future version, integer keys will always be treated as labels (consistent with DataFrame behavior). To access a value by position, use `ser.iloc[pos]`
  intercept = torch.tensor([df['coefficient'][0]])

Linear model#

[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': 'Lee, Yunsung, et al. "Blood-based epigenetic estimators of '
             'chronological age in human adults using DNA methylation data '
             'from the Illumina MethylationEPIC array." BMC genomics 21 '
             '(2020): 1-13.',
 'clock_name': 'abec',
 'data_type': 'methylation',
 'doi': 'https://doi.org/10.1186/s12864-020-07168-8',
 '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: ['cg00003407', 'cg00012238', 'cg00046991', 'cg00106564', 'cg00136547', 'cg00148423', 'cg00154159', 'cg00172371', 'cg00173854', 'cg00186842', 'cg00224487', 'cg00239061', 'cg00241002', 'cg00245896', 'cg00292452', 'cg00295303', 'cg00307557', 'cg00382859', 'cg00399614', 'cg00444360', 'cg00460268', 'cg00462994', 'cg00481951', 'cg00489183', 'cg00492055', 'cg00496676', 'cg00499787', 'cg00503832', 'cg00530720', 'cg00536366']... [Total elements: 1695]
base_model_features: None

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

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

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

base_model.linear.weight: [-0.9167025685310364, -0.02640557661652565, 4.398547649383545, 0.18068689107894897, 0.17831997573375702, 0.5542836785316467, 0.14806507527828217, -0.489886611700058, -0.2775489091873169, 0.05604557320475578, 0.10254067927598953, -2.105708360671997, -1.2334290742874146, 0.0348559245467186, -4.622097969055176, -0.022087493911385536, 0.08421055972576141, 0.6329579949378967, 0.47517868876457214, -0.21065407991409302, -0.4903133511543274, 3.060950517654419, 0.7235202789306641, 0.008708810433745384, 0.18117490410804749, -0.6214583516120911, -0.388788104057312, 0.18904635310173035, -0.9561805129051208, 0.08860684931278229]... [Tensor of shape torch.Size([1, 1695])]
base_model.linear.bias: tensor([53.6824])

%==================================== 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([[ 56.9250],
        [102.8789],
        [140.7010],
        [ 26.7447],
        [ 54.7763],
        [ 72.5397],
        [-29.5202],
        [-38.1370],
        [-11.4511],
        [-11.4444]], 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