MammalianLifespan#
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.MammalianLifespan)
class MammalianLifespan(pyagingModel):
def __init__(self):
super().__init__()
def preprocess(self, x):
return x
def postprocess(self, x):
"""
Applies an anti-log transformation.
"""
return torch.exp(x)
[3]:
model = pya.models.MammalianLifespan()
Define clock metadata#
[4]:
model.metadata["clock_name"] = "mammalianlifespan"
model.metadata["data_type"] = "DNA methylation" # Paper: The model is based on DNA methylation measurements.
model.metadata["species"] = "multiple species" # Paper: The study samples are multi.
model.metadata["year"] = 2024
model.metadata["approved_by_author"] = "⌛"
model.metadata["citation"] = "Li, Caesar Z., et al. \"Epigenetic predictors of species maximum life span and other life-history traits in mammals.\" Science Advances 10.23 (2024): eadm7273."
model.metadata["doi"] = "https://doi.org/10.1126/sciadv.adm7273"
model.metadata["notes"] = "Pan-mammalian tissue-agnostic elastic-net predictor fitted to log species maximum life span from conserved CpG methylation; pyaging exponentiates the linear output to years."
model.metadata["research_only"] = None
model.metadata["tissue"] = ["multi-tissue"] # Paper: These samples spanned 59 unique tissue types and originated from 348 distinct mammalian species across 25 taxonomic orders.
model.metadata["predicts"] = ["species maximum lifespan"] # Paper: We will refer to the predicted maximum life span, expressed in log years, as either the epigenetic maximum life span or DNAm maximum life span.
model.metadata["training_target"] = ["species maximum lifespan"] # Paper: We used three distinct penalized regression models to predict the log-transformed values of maximum life span, gestation time, and age at sexual maturity for each species.
model.metadata["unit"] = ["years"] # Paper: We will refer to the predicted maximum life span, expressed in log years, as either the epigenetic maximum life span or DNAm maximum life span.
model.metadata["model_type"] = "elastic net regression" # Paper: First, we used elastic net regression models to predict maximum life span using both CpG methylation data and taxonomic order indicators.
model.metadata["platform"] = ["Horvath MammalMethylChip40"] # Paper: All data were generated using the mammalian methylation array (HorvathMammalMethylChip40), which provides high sequencing depth of highly conserved CpGs in mammals.
model.metadata["population"] = "multiple mammalian species" # Paper: Leveraging our publicly accessible data from the Mammalian Methylation Consortium, we focused on highly conserved cytosine methylation profiles from n = 15,000 DNA samples. These samples spanned 59 unique tissue types and originated from 348 distinct mammalian species across 25 taxonomic orders.
model.metadata["journal"] = "Science Advances"
model.metadata["last_author"] = "Steve Horvath"
model.metadata["n_features"] = 152 # Paper: The official LifespanPredictor_40K_Li2021.csv contains 152 nonzero non-intercept CpG coefficients.
model.metadata["citations"] = 5
model.metadata["citations_date"] = "2026-07-05"
Download clock dependencies#
Download GitHub repository#
[5]:
github_url = "https://github.com/caeseriousli/MammalianMethylationPredictors.git"
github_folder_name = github_url.split('/')[-1].split('.')[0]
os.system(f"git clone {github_url}")
[5]:
0
Load features#
From CSV file#
[6]:
df = pd.read_csv('MammalianMethylationPredictors/Predictors/LifespanPredictor_40K_Li2021.csv')
df['feature'] = df['CpG']
df['coefficient'] = df['Coefficient']
df = df[df.Coefficient != 0]
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]])
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 = [0.5] * len(model.features)
Load preprocess and postprocess objects#
[10]:
model.preprocess_name = None
model.preprocess_dependencies = None
[11]:
model.postprocess_name = 'anti_log'
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': 'Li, Caesar Z., et al. "Epigenetic predictors of species maximum '
'lifespan and other life history traits in mammals." bioRxiv '
'(2023): 2023-11.',
'clock_name': 'mammalianlifespan',
'data_type': 'methylation',
'doi': 'https://doi.org/10.1101/2023.11.02.565286',
'notes': None,
'research_only': None,
'species': 'multi',
'version': None,
'year': 2023}
reference_values: [0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5]... [Total elements: 152]
preprocess_name: None
preprocess_dependencies: None
postprocess_name: 'anti_log'
postprocess_dependencies: None
features: ['cg00039845', 'cg00300233', 'cg00810217', 'cg01020408', 'cg01266508', 'cg01309159', 'cg01786675', 'cg02476543', 'cg02574410', 'cg02725055', 'cg02871478', 'cg03230916', 'cg03264110', 'cg03280886', 'cg03528345', 'cg03537184', 'cg03684591', 'cg03820088', 'cg04065686', 'cg04118146', 'cg04313551', 'cg04324237', 'cg04486940', 'cg04499301', 'cg04725401', 'cg04918691', 'cg04958799', 'cg05035746', 'cg05039938', 'cg05151611']... [Total elements: 152]
base_model_features: None
%==================================== Model Details ====================================%
Model Structure:
base_model: LinearModel(
(linear): Linear(in_features=152, out_features=1, bias=True)
)
%==================================== Model Details ====================================%
Model Parameters and Weights:
base_model.linear.weight: [0.04147933050990105, 0.4304673969745636, 0.07260479032993317, 0.10754379630088806, 0.05837688222527504, 0.21564741432666779, 0.22965361177921295, 0.0423436276614666, -0.6524762511253357, -0.3474166989326477, 0.05646226927638054, 0.046050943434238434, -0.03867235779762268, -0.14654619991779327, 0.29777470231056213, -0.22357487678527832, 0.19166646897792816, 0.015969855710864067, 0.12260589003562927, 0.07850058376789093, 0.11844679713249207, 0.1271219253540039, -0.3257320821285248, -0.0814819186925888, 0.1456708163022995, 0.037799667567014694, 0.19944973289966583, -0.14140872657299042, -0.0007183622219599783, 0.28238773345947266]... [Tensor of shape torch.Size([1, 152])]
base_model.linear.bias: tensor([-2.8285])
%==================================== 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([[1.8245e+00],
[7.4422e-04],
[1.6053e+00],
[2.6872e-01],
[3.1673e-03],
[2.4528e+01],
[5.4639e+00],
[1.6672e-02],
[1.2177e-01],
[1.5087e-02]], dtype=torch.float64, grad_fn=<ExpBackward0>)
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 folder: MammalianMethylationPredictors