Meer#

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

    def preprocess(self, x):
        return x

    def postprocess(self, x):
        """
        Transforms age in days to age in months.
        """
        return x / 30.5

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

Define clock metadata#

[4]:
model.metadata["clock_name"] = "meer"
model.metadata["data_type"] = "DNA methylation"  # Paper: A whole-lifespan mouse multi-tissue DNA methylation age predictor.
model.metadata["species"] = "Mus musculus"  # Paper: A whole-lifespan mouse multi-tissue DNA methylation age predictor.
model.metadata["year"] = 2018
model.metadata["approved_by_author"] = "⌛"
model.metadata["citation"] = "Meer, M. V., Podolskiy, D. I., Tyshkovskiy, A. & Gladyshev, V. N. A whole lifespan mouse multi-tissue DNA methylation clock. eLife 7, e40675 (2018)."
model.metadata["doi"] = "https://doi.org/10.7554/elife.40675"
model.metadata["notes"] = "Whole Lifespan Multi-Tissue (WLMT) mouse clock trained by elastic net on RRBS methylation percentages from untreated wild-type C57BL/6 samples."
model.metadata["research_only"] = None
model.metadata["tissue"] = ["multi-tissue"]  # Paper: The combined dataset represented 11 tissues and cell types.
model.metadata["predicts"] = ["chronological age"]  # Paper: A whole-lifespan mouse multi-tissue DNA methylation age predictor.
model.metadata["training_target"] = ["chronological age"]  # Paper: The method is based on chronological age.
model.metadata["unit"] = ["days"]  # Paper: Training and test MAE were reported in days.
model.metadata["model_type"] = "elastic net regression"  # Paper: Elastic net regression with 10-fold cross-validation.
model.metadata["platform"] = ["RRBS"]  # Paper: Only RRBS data were used to construct the clock.
model.metadata["population"] = "mice"  # Paper: Mice ranged from 1 week to 35 months; untreated wild-type C57BL/6 were used.
model.metadata["journal"] = "eLife"
model.metadata["last_author"] = "Vadim N. Gladyshev"
model.metadata["n_features"] = 435
model.metadata["citations"] = 203
model.metadata["citations_date"] = "2026-07-05"

Download clock dependencies#

Download directly with curl#

[5]:
supplementary_url = "https://elifesciences.org/download/aHR0cHM6Ly9jZG4uZWxpZmVzY2llbmNlcy5vcmcvYXJ0aWNsZXMvNDA2NzUvZWxpZmUtNDA2NzUtc3VwcDMtdjIueGxzeA--/elife-40675-supp3-v2.xlsx?_hash=qzOMc4yUFACfDFG%2FlgxkFTHWt%2BSXSmP9zz1BM3oOTRM%3D"
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', sheet_name='Whole lifespan multi-tissue', nrows=435)
df['feature'] = df['Chromosome'].astype(str) + ':' + df['Position'].astype(int).astype(str)
df['coefficient'] = df['Weight']*100

model.features = features = df['feature'].tolist()

Load weights into base model#

[7]:
weights = torch.tensor(df['coefficient'].tolist()).unsqueeze(0)
intercept = torch.tensor([234.64])

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': 'Meer, Margarita V., et al. "A whole lifespan mouse multi-tissue '
             'DNA methylation clock." Elife 7 (2018): e40675.',
 'clock_name': 'meer',
 'data_type': 'methylation',
 'doi': 'https://doi.org/10.7554/eLife.40675',
 'notes': None,
 'research_only': None,
 'species': 'Mus musculus',
 'version': None,
 'year': 2018}
reference_values: None
preprocess_name: None
preprocess_dependencies: None
postprocess_name: None
postprocess_dependencies: None
features: ['chr10:111559529', 'chr10:115250413', 'chr10:118803606', 'chr10:121498258', 'chr10:127620127', 'chr10:19970189', 'chr10:19970209', 'chr10:33624567', 'chr10:42644582', 'chr10:4621215', 'chr10:57795976', 'chr10:60698046', 'chr10:61828281', 'chr10:63820265', 'chr10:67979197', 'chr10:68137630', 'chr10:75014983', 'chr10:78273866', 'chr10:78487669', 'chr10:80182188', 'chr10:80534973', 'chr10:84760142', 'chr11:100367639', 'chr11:102255939', 'chr11:107372077', 'chr11:114423667', 'chr11:114479395', 'chr11:115989660', 'chr11:116515706', 'chr11:117175709']... [Total elements: 435]
base_model_features: None

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

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

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

base_model.linear.weight: [9.368049621582031, -4.492888927459717, -2.932995080947876, -2.1226966381073, -16.623489379882812, -2.7541234493255615, -9.462428092956543, 15.378312110900879, 22.142602920532227, 2.114746570587158, -7.513723373413086, 11.303533554077148, -12.452217102050781, -0.46204015612602234, -14.366745948791504, -9.18408203125, -6.437520503997803, -8.584598541259766, -7.610683917999268, -6.5796918869018555, 5.641702175140381, 1.8415330648422241, -12.470565795898438, 1.1288938522338867, -17.48339080810547, 14.172774314880371, 0.42071831226348877, -0.3068951964378357, 0.634797215461731, 6.434844493865967]... [Tensor of shape torch.Size([1, 435])]
base_model.linear.bias: tensor([234.6400])

%==================================== 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([[20.9082],
        [ 4.7668],
        [17.3136],
        [12.6321],
        [-2.8595],
        [ 1.7717],
        [-4.0258],
        [ 8.8037],
        [21.6245],
        [13.8154]], dtype=torch.float64, grad_fn=<DivBackward0>)

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