RepliTaliNorm#
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.RepliTaliNorm)
class RepliTaliNorm(LinearReferenceClock):
pass
[3]:
model = pya.models.RepliTaliNorm()
Define clock metadata#
[4]:
model.metadata["clock_name"] = "replitalinorm"
model.metadata["data_type"] = "DNA methylation" # Paper: Both models use DNA methylation at CpGs in common partially methylated domains.
model.metadata["species"] = "Homo sapiens" # Paper: The models were developed in primary human cells.
model.metadata["year"] = 2022
model.metadata["approved_by_author"] = "⌛"
model.metadata["citation"] = "Endicott, J.L., Nolte, P.A., Shen, H. & Laird, P.W. Cell division drives DNA methylation loss in late-replicating domains in primary human cells. Nature Communications 13, 6659 (2022)."
model.metadata["doi"] = "https://doi.org/10.1038/s41467-022-34268-8"
model.metadata["notes"] = "Upstream starting-PD normalization model used during RepliTali construction. It was trained only in the chronologically youngest fetal skin fibroblast line (AG06561) to estimate the unobserved pre-culture replicative-history offset; it is not the final 87-CpG RepliTali model."
model.metadata["research_only"] = None
model.metadata["tissue"] = ["cultured fibroblasts"] # Paper: The normalizer was trained on the chronologically youngest primary cell, fetal skin fibroblast AG06561.
model.metadata["predicts"] = ["replicative history"] # Paper: The model estimates the starting-passage PD used to correct unknown pre-culture cell divisions.
model.metadata["training_target"] = ["population doublings"] # Paper: The normalizer was fitted to the measured PD trajectory of AG06561.
model.metadata["unit"] = ["population doublings"] # Paper: The calibration outcome is cumulative population doublings.
model.metadata["model_type"] = "elastic net regression" # Paper: Both the starting-PD normalizer and final RepliTali use elastic-net regression with alpha 0.5.
model.metadata["platform"] = ["Illumina EPIC"] # Paper: Training methylation was measured using the Infinium MethylationEPIC array.
model.metadata["population"] = "human cell cultures" # Paper: Only the chronologically youngest fetal fibroblast line was used to train the starting-PD normalizer.
model.metadata["journal"] = "Nature Communications"
model.metadata["last_author"] = "Peter W. Laird"
model.metadata["n_features"] = 218
model.metadata["citations"] = 86
model.metadata["citations_date"] = "2026-07-05"
Download clock dependencies#
[5]:
os.system(f"curl -sL -o RepliTaliNorm_CpGs.rda https://raw.githubusercontent.com/HigginsChenLab/methylCIPHER/19b12296b0d7eb7055a97d068064df635f44ce3e/data/RepliTaliNorm_CpGs.rda")
os.system(f"curl -sL -o RepliTaliNorm_ref.rda https://raw.githubusercontent.com/HigginsChenLab/methylCIPHER/19b12296b0d7eb7055a97d068064df635f44ce3e/data/RepliTaliNorm_ref.rda")
[5]:
0
[6]:
%%writefile download.r
library(jsonlite)
load("RepliTaliNorm_CpGs.rda")
load("RepliTaliNorm_ref.rda")
write_json(RepliTaliNorm_CpGs, "coefficients.json", digits = 10)
write_json(RepliTaliNorm_ref$intercept, "intercept.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()
iv = json.load(open('intercept.json'))
intercept_value = iv[0] if isinstance(iv, list) else iv
Load weights into base model#
[9]:
weights = torch.tensor(coef_df['coefficient'].tolist()).unsqueeze(0).float()
intercept = torch.tensor([intercept_value]).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': 'Endicott, Jamie L., et al. "Cell division drives DNA methylation '
'loss in late-replicating domains in primary human cells." Nature '
'Communications 13.1 (2022): 6659.',
'clock_name': 'replitalinorm',
'data_type': 'methylation',
'doi': 'https://doi.org/10.1038/s41467-022-34268-8',
'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: ['cg00065944', 'cg00077044', 'cg00156723', 'cg00278655', 'cg00434151', 'cg00564996', 'cg00824087', 'cg00832327', 'cg01052456', 'cg01129509', 'cg01249202', 'cg01463644', 'cg01922998', 'cg02002355', 'cg02110836', 'cg02148017', 'cg02576202', 'cg02607176', 'cg02653473', 'cg03041877', 'cg03137548', 'cg03257387', 'cg03312661', 'cg03364201', 'cg03445914', 'cg03464371', 'cg03490300', 'cg03644817', 'cg04246882', 'cg04395911']... [Total elements: 218]
base_model_features: None
%==================================== Model Details ====================================%
Model Structure:
base_model: LinearModel(
(linear): Linear(in_features=218, out_features=1, bias=True)
)
%==================================== Model Details ====================================%
Model Parameters and Weights:
base_model.linear.weight: [-0.6055963635444641, -1.0204650163650513, -0.39693695306777954, -0.13793666660785675, -0.19817344844341278, -0.4360240697860718, -0.005339149385690689, -0.6537990570068359, -0.4812646210193634, -1.2297855615615845, -0.5315495133399963, -0.41737160086631775, -0.3746994137763977, -1.131536602973938, -0.010423482395708561, -0.3394857943058014, -0.2915678024291992, -2.6015284061431885, -0.0052614822052419186, -0.27036532759666443, -2.179006814956665, 0.6976109147071838, -1.055829405784607, -0.5952957272529602, -0.0049955337308347225, 0.4774562418460846, -1.847993016242981, -0.5958481431007385, -0.1950979232788086, -0.007305147126317024]... [Tensor of shape torch.Size([1, 218])]
base_model.linear.bias: tensor([75.8801])
%==================================== 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([[76.1917],
[62.6222],
[78.3400],
[75.3361],
[71.4866],
[67.6907],
[74.4185],
[71.8606],
[72.5646],
[88.5451]], 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: intercept.json
Deleted file: download.r
Deleted file: RepliTaliNorm_CpGs.rda
Deleted file: RepliTaliNorm_ref.rda
Deleted file: coefficients.json