DNAmTL#

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

    def preprocess(self, x):
        return x

    def postprocess(self, x):
        return x

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

Define clock metadata#

[4]:
model.metadata["clock_name"] = "dnamtl"
model.metadata["data_type"] = "DNA methylation"  # Paper: methylation
model.metadata["species"] = "Homo sapiens"  # Paper: Homo sapiens
model.metadata["year"] = 2019
model.metadata["approved_by_author"] = "⌛"
model.metadata["citation"] = "Lu, A. T., et al. \"DNA methylation-based estimator of telomere length.\" Aging 11.16 (2019): 5895-5923."
model.metadata["doi"] = "https://doi.org/10.18632/aging.102173"
model.metadata["notes"] = "Elastic-net blood DNA-methylation estimator of measured leukocyte telomere length, using 140 CpGs shared by the Illumina 450K and EPIC arrays and returning kilobases."
model.metadata["research_only"] = None
model.metadata["tissue"] = ["whole blood"]  # Paper: whole blood (leukocytes)
model.metadata["predicts"] = ["leukocyte telomere length"]  # Paper: leukocyte telomere length
model.metadata["training_target"] = ["leukocyte telomere length"]  # Paper: measured leukocyte telomere length (mean terminal restriction fragment)
model.metadata["unit"] = ["kilobases"]  # Paper: kilobases
model.metadata["model_type"] = "elastic net regression"  # Paper: Elastic net
model.metadata["platform"] = ["Illumina 450K", "Illumina EPIC"]  # Paper: Illumina 450K/EPIC
model.metadata["population"] = "adults"  # Paper: human blood training set: 2,256 adults aged 22–93 years
model.metadata["journal"] = "Aging"
model.metadata["last_author"] = "Steve Horvath"
model.metadata["n_features"] = 140
model.metadata["citations"] = 461
model.metadata["citations_date"] = "2026-07-05"

Download clock dependencies#

Download directly with curl#

[5]:
supplementary_url = "https://www.aging-us.com/article/102173/supplementary/SD7/0/aging-v11i16-102173-supplementary-material-SD7.xlsx"
supplementary_file_name = "coefficients.xlsx"
os.system(f"curl -o {supplementary_file_name} {supplementary_url}")
[5]:
0

Load features#

From Excel file#

[6]:
df = pd.read_excel('coefficients.xlsx', skiprows=5)
model.features = df['Variable'][1:].tolist()

Load weights into base model#

[7]:
weights = torch.tensor(df['Coefficient'][1:].tolist()).unsqueeze(0).float()
intercept = torch.tensor([df['Coefficient'][0]]).float()

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': 'Lu, Ake T., et al. "DNA methylation-based estimator of telomere '
             'length." Aging (Albany NY) 11.16 (2019): 5895.',
 'clock_name': 'dnamtl',
 'data_type': 'methylation',
 'doi': 'https://doi.org/10.18632/aging.102173',
 'notes': None,
 'research_only': None,
 'species': 'Homo sapiens',
 'version': None,
 'year': 2019}
reference_values: None
preprocess_name: None
preprocess_dependencies: None
postprocess_name: None
postprocess_dependencies: None
features: ['cg05528516', 'cg00060374', 'cg12711627', 'cg06853416', 'cg01901101', 'cg21393163', 'cg22866430', 'cg16047567', 'cg18768612', 'cg24049493', 'cg08893087', 'cg03984502', 'cg19233405', 'cg05694771', 'cg24739596', 'cg06370057', 'cg24457743', 'cg18148156', 'cg19935065', 'cg10549018', 'cg24903144', 'cg17782974', 'cg13357922', 'cg23908305', 'cg15742496', 'cg27639942', 'cg27312916', 'cg02121547', 'cg26827653', 'cg16593899']... [Total elements: 140]
base_model_features: None

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

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

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

base_model.linear.weight: [-0.034901853650808334, 0.19265501201152802, 0.17826975882053375, 0.05488372966647148, -0.2881372272968292, 0.23130665719509125, -0.1323840469121933, 0.27831143140792847, 0.03168892487883568, -0.14803270995616913, 0.16454507410526276, -1.5903596878051758, -0.23612754046916962, -0.1190737932920456, -0.06489834934473038, -0.04797552898526192, 0.04501348361372948, -0.3370150625705719, -0.07192609459161758, -0.10779186338186264, -0.028722835704684258, -0.24827733635902405, 0.11593383550643921, 0.19950832426548004, 0.06547325104475021, -0.031409118324518204, -0.3067828118801117, 0.053266491740942, 0.06589461863040924, 0.3522004783153534]... [Tensor of shape torch.Size([1, 140])]
base_model.linear.bias: tensor([7.9248])

%==================================== 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([[ 8.6703],
        [10.1749],
        [ 5.3619],
        [ 8.5101],
        [ 5.2568],
        [ 6.5989],
        [ 6.2494],
        [10.8052],
        [ 8.0483],
        [10.3405]], 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.xlsx