DNAmIC#
Index#
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.DNAmIC)
class DNAmIC(pyagingModel):
def __init__(self):
super().__init__()
def preprocess(self, x):
return x
def postprocess(self, x):
return x
[3]:
model = pya.models.DNAmIC()
Define clock metadata#
[4]:
model.metadata["clock_name"] = 'dnamic'
model.metadata["data_type"] = 'methylation'
model.metadata["species"] = 'Homo sapiens'
model.metadata["year"] = 2025
model.metadata["approved_by_author"] = '⌛'
model.metadata["citation"] = "Fuentealba, M., Rouch, L., Guyonnet, S. et al. A blood-based epigenetic clock for intrinsic capacity predicts mortality and is associated with clinical, immunological and lifestyle factors. Nat Aging (2025)."
model.metadata["doi"] = 'https://doi.org/10.1038/s43587-025-00883-5'
model.metadata["research_only"] = None
model.metadata["notes"] = None
Download clock dependencies#
Download directly with curl#
[5]:
supplementary_url = "https://static-content.springer.com/esm/art%3A10.1038%2Fs43587-025-00883-5/MediaObjects/43587_2025_883_MOESM2_ESM.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=1)
model.features = df['feature'][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': 'Fuentealba, M., Rouch, L., Guyonnet, S. et al. A blood-based '
'epigenetic clock for intrinsic capacity predicts mortality and '
'is associated with clinical, immunological and lifestyle '
'factors. Nat Aging (2025).',
'clock_name': 'dnamic',
'data_type': 'methylation',
'doi': 'https://doi.org/10.1038/s43587-025-00883-5',
'notes': None,
'research_only': None,
'species': 'Homo sapiens',
'version': None,
'year': 2025}
reference_values: None
preprocess_name: None
preprocess_dependencies: None
postprocess_name: None
postprocess_dependencies: None
features: ['cg06846752', 'cg19916364', 'cg05781609', 'cg15726426', 'cg10389771', 'cg16269733', 'cg03890680', 'cg16052388', 'cg13022624', 'cg12387232', 'cg11176990', 'cg22158769', 'cg00740914', 'cg11807280', 'cg07337544', 'cg00528640', 'cg22454769', 'cg19074170', 'cg17165841', 'cg14435073', 'cg00870633', 'cg12340144', 'cg03607117', 'cg07144720', 'cg25265234', 'cg27182476', 'cg24850932', 'cg03915012', 'cg03799405', 'cg25144207']... [Total elements: 91]
base_model_features: None
%==================================== Model Details ====================================%
Model Structure:
base_model: LinearModel(
(linear): Linear(in_features=91, out_features=1, bias=True)
)
%==================================== Model Details ====================================%
Model Parameters and Weights:
base_model.linear.weight: [-0.023061953485012054, 0.028366349637508392, 0.06697678565979004, -0.005531138274818659, -0.020453236997127533, -0.003387788310647011, 0.004279314540326595, -0.00794045440852642, -0.1964813619852066, 0.025699475780129433, -0.022459663450717926, -0.08036743849515915, 0.003675997955724597, 0.008809729479253292, -0.038982685655355453, 0.01619679480791092, -0.07418529689311981, -0.016918139532208443, -0.008944512344896793, -0.005050707142800093, -0.0020198391284793615, 0.06946389377117157, -0.17613497376441956, 0.02284012921154499, 0.006404522340744734, 0.017410462722182274, 0.01889532431960106, 0.03263133391737938, 0.037918440997600555, -0.003133830614387989]... [Tensor of shape torch.Size([1, 91])]
base_model.linear.bias: tensor([0.7853])
%==================================== 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.6556],
[1.2822],
[0.8457],
[0.8393],
[0.1830],
[0.7785],
[0.5989],
[0.1055],
[0.5754],
[0.8244]], 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