Thompson#

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

    def preprocess(self, x):
        return x

    def postprocess(self, x):
        return x

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

Define clock metadata#

[4]:
model.metadata["clock_name"] = "thompson"
model.metadata["data_type"] = "DNA methylation"  # Paper: The clocks use mouse CpG DNA-methylation frequencies.
model.metadata["species"] = "Mus musculus"  # Paper: The study develops full-lifespan epigenetic clocks for mice.
model.metadata["year"] = 2018
model.metadata["approved_by_author"] = "✅"
model.metadata["citation"] = "Thompson, M. J., Chwiałkowska, K., Rubbi, L. et al. A multi-tissue full lifespan epigenetic clock for mice. Aging (Albany NY) 10, 2832–2854 (2018)."
model.metadata["doi"] = "https://doi.org/10.18632/aging.101590"
model.metadata["notes"] = "Full-lifespan multi-tissue mouse DNA-methylation clock fit by elastic net to RRBS CpG methylation across 1,147 samples from ten tissues and multiple strains; the 582-site all-CpG model estimates chronological age and detects intervention- and genotype-associated age acceleration."
model.metadata["research_only"] = None
model.metadata["tissue"] = ["adipose tissue", "blood", "cerebellum", "brain cortex", "heart", "kidney", "liver", "lung", "skeletal muscle", "spleen"]  # Paper: Table 2 lists adipose, blood, kidney, liver, lung, muscle, cortex, heart, cerebellum, and spleen datasets.
model.metadata["predicts"] = ["chronological age"]  # Paper: The clock estimates chronological age at DNA sample collection.
model.metadata["training_target"] = ["chronological age"]  # Paper: Penalized regression predicts sample chronological age in months from CpG methylation.
model.metadata["unit"] = ["months"]  # Paper: Age errors and predictions are reported in months, and the released workflow returns predicted age in months.
model.metadata["model_type"] = "elastic net regression"  # Paper: The all-CpG clock uses elastic net with alpha equal to 0.5.
model.metadata["platform"] = ["RRBS"]  # Paper: Methylation was measured with reduced-representation bisulfite sequencing.
model.metadata["population"] = "mice"  # Paper: The combined datasets span prenatal age through 32.2 months and include C57BL/6, BALB/c, Diversity Outbred, dwarf, GHRKO, and HMDP strains.
model.metadata["journal"] = "Aging (Albany NY)"
model.metadata["last_author"] = "Matteo Pellegrini"
model.metadata["n_features"] = 582
model.metadata["citations"] = 236
model.metadata["citations_date"] = "2026-07-05"

Download clock dependencies#

Download GitHub repository#

[5]:
github_url = "https://github.com/kerepesi/MouseAgingClocks.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_table('MouseAgingClocks/ClockData/Thompson2018-ElasticNet_aging_clock.txt', skiprows=1)
intercept = df['Coefficient'].iloc[0]
df = df[1:]
df['feature'] = df['Chromosome'].astype(str) + ':' + df['Coordinate'].astype(int).astype(str)
df['coefficient'] = df['Coefficient']

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

Load weights into base model#

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

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': 'Thompson, Michael J., et al. "A multi-tissue full lifespan '
             'epigenetic clock for mice." Aging (Albany NY) 10.10 (2018): '
             '2832.',
 'clock_name': 'thompson',
 'data_type': 'methylation',
 'doi': 'https://doi.org/10.18632/aging.101590',
 '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: ['chr1:9967422', 'chr1:9967428', 'chr1:13126576', 'chr1:15286937', 'chr1:46800385', 'chr1:55087536', 'chr1:63273286', 'chr1:63273288', 'chr1:64690282', 'chr1:71603645', 'chr1:79761546', 'chr1:79858375', 'chr1:84695279', 'chr1:84934769', 'chr1:89455649', 'chr1:92848744', 'chr1:92848748', 'chr1:95666316', 'chr1:103479589', 'chr1:105270925', 'chr1:106758726', 'chr1:118310888', 'chr1:118311288', 'chr1:119648512', 'chr1:120602265', 'chr1:120602331', 'chr1:128359556', 'chr1:132331689', 'chr1:132937328', 'chr1:135374481']... [Total elements: 582]
base_model_features: None

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

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

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

base_model.linear.weight: [0.7605000138282776, 0.12610000371932983, 4.3765997886657715, 5.6855998039245605, -0.5194000005722046, -0.6355000138282776, 0.41659998893737793, 1.2926000356674194, 5.576700210571289, -0.9544000029563904, -5.0493998527526855, -0.2711000144481659, 0.24879999458789825, -0.8901000022888184, 0.7444000244140625, 0.03920000046491623, 0.40560001134872437, -2.0560998916625977, 0.5519000291824341, -0.663100004196167, -0.8413000106811523, -3.921999931335449, -3.1031999588012695, -1.9629000425338745, 2.824700117111206, -0.3255000114440918, 1.7187999486923218, -1.5643999576568604, -0.7063000202178955, -2.196000099182129]... [Tensor of shape torch.Size([1, 582])]
base_model.linear.bias: tensor([30.3172])

%==================================== 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([[102.1936],
        [ 83.5008],
        [ 61.2582],
        [-60.8014],
        [-27.0123],
        [ 77.8211],
        [ 51.7655],
        [ 57.8975],
        [167.7028],
        [ 52.8332]], 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 folder: MouseAgingClocks