RetroelementAgeV2¶
Index¶
Let’s first import some packages:
[1]:
import os
import inspect
import shutil
import json
import math
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.RetroelementAgeV2)
class RetroelementAgeV2(pyagingModel):
def __init__(self):
super().__init__()
def preprocess(self, x):
return x
def postprocess(self, x):
return x
[3]:
model = pya.models.RetroelementAgeV2()
Define clock metadata¶
[4]:
model.metadata["clock_name"] = "retroelementagev2"
model.metadata["data_type"] = "DNA methylation" # Paper: blood DNA methylation
model.metadata["species"] = "Homo sapiens" # Paper: 12,670 people
model.metadata["year"] = 2024
model.metadata["approved_by_author"] = "⌛"
model.metadata["citation"] = "Ndhlovu, Lishomwa C., et al. \"Retro-age: A unique epigenetic biomarker of aging captured by DNA methylation states of retroelements.\" Aging Cell 23 (2024): e14288."
model.metadata["doi"] = "https://doi.org/10.1111/acel.14288"
model.metadata["notes"] = "Composite Retroelement-Age V2 extends the retroelement annotation to CpGs compatible across EPIC v1.0 and v2.0 and was trained by 10-fold-cross-validated elastic net."
model.metadata["research_only"] = None
model.metadata["tissue"] = ["whole blood"] # Paper: DNA methylation data generated from whole blood
model.metadata["predicts"] = ["chronological age"] # Paper: CpG sites predictive of chronological age
model.metadata["training_target"] = ["chronological age"] # Paper: chronological ages ranging from 12 to 100 years old
model.metadata["unit"] = ["years"] # Paper: chronological ages ranging from 12 to 100 years
model.metadata["model_type"] = "elastic net regression" # Paper: generalized linear elastic net model ... 10-fold cross-validation
model.metadata["platform"] = ["Illumina EPIC"] # Paper: EPIC v.1.0 and v.2.0 compatible
model.metadata["population"] = "all ages" # Paper: 12,670 people ... ages ranging from 12 to 100 years old
model.metadata["journal"] = "Aging Cell"
model.metadata["last_author"] = "Michael J. Corley"
model.metadata["n_features"] = 1378
model.metadata["citations"] = 31
model.metadata["citations_date"] = '2026-10-02'
Download clock dependencies¶
Download directly with curl¶
[5]:
supplementary_url = "https://zenodo.org/records/11099870/files/Retroelement_AgeV2coefficients.csv?download=1"
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['feature'] = df['name']
model.features = df['feature'].tolist()[1:]
Load weights into base model¶
[7]:
weights = torch.tensor(df['coefficient'].tolist()[1:]).unsqueeze(0)
intercept = torch.tensor([df['coefficient'].tolist()[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': 'Ndhlovu, Lishomwa C., et al. "Retro-age: A unique epigenetic '
'biomarker of aging captured by DNA methylation states of '
'retroelements." Aging Cell 23 (2024): e14288.',
'citations': 31,
'citations_date': '2026-10-02',
'clock_name': 'retroelementagev2',
'data_type': 'DNA methylation',
'doi': 'https://doi.org/10.1111/acel.14288',
'journal': 'Aging Cell',
'last_author': 'Michael J. Corley',
'model_type': 'elastic net regression',
'n_features': 1378,
'notes': 'Composite Retroelement-Age V2 extends the retroelement annotation '
'to CpGs compatible across EPIC v1.0 and v2.0 and was trained by '
'10-fold-cross-validated elastic net.',
'platform': ['Illumina EPIC'],
'population': 'all ages',
'predicts': ['chronological age'],
'research_only': None,
'species': 'Homo sapiens',
'tissue': ['whole blood'],
'training_target': ['chronological age'],
'unit': ['years'],
'version': '0.5.7',
'year': 2024}
reference_values: None
preprocess_name: None
preprocess_dependencies: None
postprocess_name: None
postprocess_dependencies: None
features: ['cg23728960', 'cg10366786', 'cg08398371', 'cg10973967', 'cg01721313', 'cg25231957', 'cg21992844', 'cg24646803', 'cg16037947', 'cg03468827', 'cg18939097', 'cg01740695', 'cg25593520', 'cg11120551', 'cg01403320', 'cg07821808', 'cg19796584', 'cg27422507', 'cg16033766', 'cg03667422', 'cg18369325', 'cg09373192', 'cg00700455', 'cg20923885', 'cg07644039', 'cg08506585', 'cg12744300', 'cg20051117', 'cg04765439', 'cg03320087']... [Total elements: 1378]
base_model_features: None
%==================================== Model Details ====================================%
Model Structure:
base_model: LinearModel(
(linear): Linear(in_features=1378, out_features=1, bias=True)
)
%==================================== Model Details ====================================%
Model Parameters and Weights:
base_model.linear.weight: [0.14868102967739105, 0.4319063127040863, -3.2955737113952637, 2.740462303161621, 0.8276747465133667, 2.5161685943603516, -1.4428094625473022, 0.7483506798744202, 0.18299150466918945, -0.6927100419998169, 0.17969781160354614, -0.10440022498369217, -1.5772448778152466, -0.6229540705680847, 0.6904758214950562, 0.16339100897312164, 0.9191771745681763, 3.9579126834869385, 0.0863616093993187, 0.5412383079528809, 0.45451620221138, 0.6237431168556213, 1.284313678741455, 0.9083895683288574, -0.12913724780082703, -0.03379112854599953, 2.2048282623291016, 3.126389503479004, -4.167088508605957, 2.5030527114868164]... [Tensor of shape torch.Size([1, 1378])]
base_model.linear.bias: tensor([62.0742])
%==================================== Model Details ====================================%
Normal feature ranges¶
[ ]:
# Units and plausibility ranges come from the package registry, keyed by feature name.
feature_ranges = pya.utils.resolve_feature_ranges(model.features, model.metadata["data_type"])
model.feature_units = [record["unit"] for record in feature_ranges]
pd.DataFrame.from_records(feature_ranges).head()
Basic test¶
[ ]:
# Exercise the clock with values in the middle of each feature's expected range.
records = pya.utils.resolve_feature_ranges(model.features, model.metadata["data_type"])
midpoints = [
(record["low"] + record["high"]) / 2 if math.isfinite(record["high"]) else max(record["low"], 1.0)
for record in records
]
input = torch.tensor([midpoints] * 10, dtype=torch.float64)
model.eval()
model.to(torch.float64)
pred = model(input)
pred
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