DNAmFILi#

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.DNAmFILi)
class DNAmFILi(LinearReferenceClock):
    pass

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

Define clock metadata#

[4]:
model.metadata["clock_name"] = 'dnamfili'
model.metadata["data_type"] = 'methylation'
model.metadata["species"] = 'Homo sapiens'
model.metadata["year"] = 2022
model.metadata["approved_by_author"] = '⌛'
model.metadata["citation"] = "Li, Xiaoyu, et al. \"A DNA methylation-based epigenetic frailty score in older adults.\" Nature Communications 13.1 (2022): 5269."
model.metadata["doi"] = "https://doi.org/10.1038/s41467-022-32893-x"
model.metadata["research_only"] = None
model.metadata["notes"] = "Blood epigenetic frailty risk score predicting a deficit-accumulation frailty index, derived by LASSO regression that selects 20 CpGs from frailty-associated methylation loci in a population-based older-adult cohort. Predicts both prevalent frailty and its incidence over up to five years of follow-up."
model.metadata["tissue"] = 'whole blood (peripheral blood)'
model.metadata["predicts"] = 'frailty risk (frailty index, prevalent and incident frailty)'
model.metadata["unit"] = 'score (arbitrary)'
model.metadata["model_type"] = 'LASSO'
model.metadata["platform"] = 'Illumina 450K/EPIC'
model.metadata["population"] = 'older adults, aged 50-75 years (ESTHER); validated in KORA-Age, age >=65'
model.metadata["journal"] = 'Nature Communications'
model.metadata["last_author"] = 'Hermann Brenner'
model.metadata["n_features"] = 20
model.metadata["citations"] = 22
model.metadata["citations_date"] = '2026-07-05'

Download clock dependencies#

[5]:
os.system(f"curl -sL -o DNAmFI_Li_CpGs.rda https://raw.githubusercontent.com/HigginsChenLab/methylCIPHER/19b12296b0d7eb7055a97d068064df635f44ce3e/data/DNAmFI_Li_CpGs.rda")
[5]:
0
[6]:
%%writefile download.r

library(jsonlite)
load("DNAmFI_Li_CpGs.rda")
write_json(DNAmFI_Li_CpGs, "coefficients.json", digits = 10)
Writing download.r
[7]:
os.system("Rscript download.r")
[7]:
0

Load features#

[8]:
coef_df = pd.DataFrame(json.load(open('coefficients.json')))
model.features = coef_df['CpG'].tolist()

Load weights into base model#

[9]:
weights = torch.tensor(coef_df['Beta'].tolist()).unsqueeze(0).float()
intercept = torch.tensor([0.204]).float()
[10]:
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#

[11]:
model.reference_values = None

Load preprocess and postprocess objects#

[12]:
model.preprocess_name = None
model.preprocess_dependencies = None
[13]:
model.postprocess_name = None
model.postprocess_dependencies = None

Check all clock parameters#

[14]:
pya.utils.print_model_details(model)

%==================================== Model Details ====================================%
Model Attributes:

training: True
metadata: {'approved_by_author': '⌛',
 'citation': 'Li, Xiaoyu, et al. "A DNA methylation-based epigenetic frailty '
             'score in older adults." Nature Communications 13.1 (2022): 5269.',
 'clock_name': 'dnamfili',
 'data_type': 'methylation',
 'doi': 'https://doi.org/10.1038/s41467-022-32893-x',
 'notes': None,
 'research_only': None,
 'species': 'Homo sapiens',
 'version': None,
 'year': 2022}
reference_values: None
preprocess_name: None
preprocess_dependencies: None
postprocess_name: None
postprocess_dependencies: None
features: ['cg00921350',
 'cg01234420',
 'cg02867102',
 'cg03725309',
 'cg04955914',
 'cg07312601',
 'cg07349348',
 'cg08463758',
 'cg10408430',
 'cg11700584',
 'cg12510708',
 'cg13570972',
 'cg15058210',
 'cg15380836',
 'cg17860366',
 'cg17971578',
 'cg18791730',
 'cg19267254',
 'cg21656937',
 'cg23458887']
base_model_features: None

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

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

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

base_model.linear.weight: tensor([[-0.2090, -0.1000, -0.0160, -0.2930, -0.1460, -0.0840,  0.1580,  0.1370,
          0.2480, -0.1010, -0.0490,  0.0640, -0.0570, -0.1800, -0.1440,  0.3150,
         -0.0750, -0.1760, -0.0250, -0.0770]])
base_model.linear.bias: tensor([0.2040])

%==================================== Model Details ====================================%

Basic test#

[15]:
torch.manual_seed(42)
input = torch.randn(10, len(model.features), dtype=float)
model.eval()
model.to(float)
pred = model(input)
pred
[15]:
tensor([[-1.3837],
        [-0.2305],
        [-0.8730],
        [ 0.7649],
        [ 0.6257],
        [ 0.3401],
        [ 0.5390],
        [-1.0176],
        [ 0.3744],
        [ 0.9479]], dtype=torch.float64, grad_fn=<AddmmBackward0>)

Save torch model#

[16]:
torch.save(model, f"../weights/{model.metadata['clock_name']}.pt")

Clear directory#

[17]:
# 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: download.r
Deleted file: DNAmFI_Li_CpGs.rda
Deleted file: coefficients.json