CellPopAge#
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.CellPopAge)
class CellPopAge(LinearReferenceClock):
pass
[3]:
model = pya.models.CellPopAge()
Define clock metadata#
[4]:
model.metadata["clock_name"] = 'cellpopage'
model.metadata["data_type"] = 'methylation'
model.metadata["species"] = 'Homo sapiens'
model.metadata["year"] = 2024
model.metadata["approved_by_author"] = '⌛'
model.metadata["citation"] = "Lujan, Gabriel M., et al. \"A DNA methylation clock to measure the epigenetic age of cell populations.\" Genome Medicine 16 (2024)."
model.metadata["doi"] = "https://doi.org/10.1186/s13073-024-01349-w"
model.metadata["research_only"] = None
model.metadata["notes"] = "DNA-methylation clock that tracks the passage-based, replicative age of cultured adult human primary cell populations from a compact set of CpGs, uniquely designed to detect deceleration of aging by candidate anti-aging compounds in vitro."
model.metadata["tissue"] = 'adult primary human fibroblasts (mammary and dermal) in culture'
model.metadata["predicts"] = 'passage-based epigenetic age of a cell population in culture'
model.metadata["unit"] = 'cell passage number'
model.metadata["model_type"] = 'Elastic net'
model.metadata["platform"] = 'Illumina EPIC'
model.metadata["population"] = 'adult primary human cells in culture'
model.metadata["journal"] = 'Genome Medicine'
model.metadata["last_author"] = 'Ivana Bjedov'
model.metadata["n_features"] = 2543
model.metadata["citations"] = 6
model.metadata["citations_date"] = '2026-07-05'
Download clock dependencies#
[5]:
os.system(f"curl -sL -o CellPopAge_ref.rda https://raw.githubusercontent.com/HigginsChenLab/methylCIPHER/19b12296b0d7eb7055a97d068064df635f44ce3e/data/CellPopAge_ref.rda")
[5]:
0
[6]:
%%writefile download.r
library(jsonlite)
load("CellPopAge_ref.rda")
write_json(CellPopAge_ref$all_CpGs, "coefficients.json", digits = 10)
write_json(CellPopAge_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': 'Lujan, Gabriel M., et al. "A DNA methylation clock to measure '
'the epigenetic age of cell populations." Genome Medicine 16 '
'(2024).',
'clock_name': 'cellpopage',
'data_type': 'methylation',
'doi': 'https://doi.org/10.1186/s13073-024-01349-w',
'notes': None,
'research_only': None,
'species': 'Homo sapiens',
'version': None,
'year': 2024}
reference_values: None
preprocess_name: None
preprocess_dependencies: None
postprocess_name: None
postprocess_dependencies: None
features: ['cg03662648', 'cg07230471', 'cg09689790', 'cg00283934', 'cg27617964', 'cg21734265', 'cg21184340', 'cg17342766', 'cg00312508', 'cg08907118', 'cg12071423', 'cg16622870', 'cg08126590', 'cg04121501', 'cg18571156', 'cg22900075', 'cg26475539', 'cg27500194', 'cg09992376', 'cg26450896', 'cg06863239', 'cg25651783', 'cg08461941', 'cg11738198', 'cg23407476', 'cg01159380', 'cg05369308', 'cg27537795', 'cg15563081', 'cg19920898']... [Total elements: 2543]
base_model_features: None
%==================================== Model Details ====================================%
Model Structure:
base_model: LinearModel(
(linear): Linear(in_features=2543, out_features=1, bias=True)
)
%==================================== Model Details ====================================%
Model Parameters and Weights:
base_model.linear.weight: [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -0.5474669337272644, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]... [Tensor of shape torch.Size([1, 2543])]
base_model.linear.bias: tensor([11.5268])
%==================================== 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([[ 8.1066],
[21.9362],
[13.3644],
[31.7122],
[30.1219],
[-3.8962],
[ 9.8756],
[-2.5270],
[ 2.6161],
[ 9.8903]], 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: coefficients.json
Deleted file: CellPopAge_ref.rda