SenMortalityAge#

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

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

Define clock metadata#

[4]:
model.metadata["clock_name"] = "senmortalityage"
model.metadata["data_type"] = "DNA methylation"  # Paper: The predictors use CpG DNA-methylation beta values.
model.metadata["species"] = "Homo sapiens"  # Paper: All three assigned predictors were developed from human cell or human whole-blood datasets.
model.metadata["year"] = 2026
model.metadata["approved_by_author"] = "⌛"
model.metadata["citation"] = "Kasamoto, K., Gibson, J., Moqri, M., Smith, R. & Higgins-Chen, A.T. DNA methylation signatures of cellular senescence are not reversed by senolytic treatment. Aging Cell 25, e70430 (2026)."
model.metadata["doi"] = "https://doi.org/10.1111/acel.70430"
model.metadata["notes"] = "Senescence-enriched elastic-net Cox predictor of mortality, restricted to direction-concordant senescence/age/mortality CpGs and trained in the Framingham Heart Study."
model.metadata["research_only"] = None
model.metadata["tissue"] = ["whole blood"]  # Paper: FHS whole-blood methylation was used for model training.
model.metadata["predicts"] = ["mortality risk"]  # Paper: SenMortalityAge is the mortality predictor among the three clocks.
model.metadata["training_target"] = ["mortality"]  # Paper: Elastic-net Cox regression was fitted to time-to-death.
model.metadata["unit"] = ["log hazard"]  # Paper: Pyaging returns the Cox linear predictor directly without exponentiation or another postprocess.
model.metadata["model_type"] = "elastic net Cox regression"  # Paper: The mortality model used elastic-net Cox regression with cross-validated lambda.
model.metadata["platform"] = ["Illumina 450K", "Illumina EPIC"]  # Paper: Feature discovery and predictor training used human 450K and EPIC methylation datasets.
model.metadata["population"] = "adults"  # Paper: The FHS cohorts comprised 2,748 Offspring and 1,457 Third Generation participants; the model used a 70/30 split.
model.metadata["journal"] = "Aging Cell"
model.metadata["last_author"] = "Albert T. Higgins-Chen"
model.metadata["n_features"] = 91
model.metadata["citations"] = 0
model.metadata["citations_date"] = "2026-07-05"

Download clock dependencies#

[5]:
os.system(f"curl -sL -o SenMortalityAge_CpGs.csv https://raw.githubusercontent.com/HigginsChenLab/methylCIPHER/19b12296b0d7eb7055a97d068064df635f44ce3e/data-raw/SenescenceAge/SenMortalityAge_CpGs.csv")
[5]:
0

Load features#

[6]:
coef_df = pd.read_csv('SenMortalityAge_CpGs.csv')
model.features = coef_df['CpG'].tolist()

Load weights into base model#

[7]:
weights = torch.tensor(coef_df['Coefficient'].tolist()).unsqueeze(0).float()
intercept = torch.tensor([0.0]).float()
[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': 'Kasamoto, Kotaro, et al. "DNA methylation clocks for estimating '
             'replicative senescence in human cells." Aging Cell (2026): '
             'e70430.',
 'clock_name': 'senmortalityage',
 'data_type': 'methylation',
 'doi': 'https://doi.org/10.1111/acel.70430',
 'notes': None,
 'research_only': None,
 'species': 'Homo sapiens',
 'version': None,
 'year': 2026}
reference_values: None
preprocess_name: None
preprocess_dependencies: None
postprocess_name: None
postprocess_dependencies: None
features: ['cg00006787', 'cg00054496', 'cg00458878', 'cg00459119', 'cg03175417', 'cg03366574', 'cg04094193', 'cg04234014', 'cg05396212', 'cg06015525', 'cg06507987', 'cg06542681', 'cg07458308', 'cg08332990', 'cg08726900', 'cg08770961', 'cg10682299', 'cg11974796', 'cg12132563', 'cg12506165', 'cg13029847', 'cg13315970', 'cg13714749', 'cg14205663', 'cg15163603', 'cg16086130', 'cg16181396', 'cg16374999', 'cg16552271', 'cg17340519']... [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.1905025690793991, 2.4848039150238037, 0.8850484490394592, 0.7116715908050537, 2.5755298137664795, 3.6517186164855957, 1.0995451211929321, 0.43131953477859497, 1.3369412422180176, 1.197675108909607, 0.7618207931518555, 0.18213650584220886, 3.231579303741455, 0.2401280403137207, 0.8895606994628906, 0.3462097942829132, 2.011119842529297, 0.7437288761138916, 0.5966653823852539, 0.6629067659378052, 0.5791985988616943, 1.4628826379776, 0.20292864739894867, 1.2046616077423096, -0.05603138357400894, 1.015661358833313, 0.6152376532554626, 0.8949704766273499, 0.13805358111858368, 0.4781338572502136]... [Tensor of shape torch.Size([1, 91])]
base_model.linear.bias: tensor([0.])

%==================================== 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([[-32.2390],
        [ 10.5977],
        [ 19.5190],
        [ -3.3155],
        [ 12.2869],
        [ 26.4824],
        [  3.7673],
        [-23.1682],
        [-18.8041],
        [ -3.3204]], 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: SenMortalityAge_CpGs.csv