Hep#
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.Hep)
class Hep(LinearReferenceClock):
pass
[3]:
model = pya.models.Hep()
Define clock metadata#
[4]:
model.metadata["clock_name"] = 'hep'
model.metadata["data_type"] = 'methylation'
model.metadata["species"] = 'Homo sapiens'
model.metadata["year"] = 2024
model.metadata["approved_by_author"] = '⌛'
model.metadata["citation"] = "Tong, Huige, et al. \"Cell-type-specific and cell-type-independent DNA methylation clocks.\" Aging 16 (2024)."
model.metadata["doi"] = "https://doi.org/10.18632/aging.206184"
model.metadata["research_only"] = None
model.metadata["notes"] = "Hepatocyte-specific DNA-methylation clock estimating chronological age within the hepatocyte compartment of liver tissue, built by LASSO regression on cell-type-specific age-associated CpGs identified through cell-type deconvolution. It detects age acceleration in liver pathologies such as NAFLD and obesity that bulk-tissue clocks miss."
model.metadata["tissue"] = 'liver (hepatocyte-specific, trained on bulk liver tissue)'
model.metadata["predicts"] = 'chronological age'
model.metadata["unit"] = 'years'
model.metadata["model_type"] = 'LASSO'
model.metadata["platform"] = 'Illumina EPIC'
model.metadata["population"] = 'adults (18-75 years)'
model.metadata["journal"] = 'Aging'
model.metadata["last_author"] = 'Andrew E. Teschendorff'
model.metadata["n_features"] = 70
model.metadata["citations"] = 25
model.metadata["citations_date"] = '2026-07-05'
Download clock dependencies#
[5]:
supplementary_url = "https://raw.githubusercontent.com/Duzhaozhen/OmniAge/c10fbe8cb92957520fbff1d55ae1def0691252e5/OmniAgePy/src/omniage/data/CTS/Hep.csv"
supplementary_file_name = "coefficients.csv"
os.system(f"curl -sL -o {supplementary_file_name} {supplementary_url}")
[5]:
0
Load features#
[6]:
df = pd.read_csv('coefficients.csv')
if str(df.columns[0]).startswith('Unnamed'):
df = df.iloc[:, 1:]
mask = df['probe'].astype(str).str.lower().isin(['intercept', '(intercept)'])
intercept_value = float(df.loc[mask, 'coef'].iloc[0]) if mask.any() else 0.0
coef_df = df.loc[~mask].reset_index(drop=True)
model.features = coef_df['probe'].tolist()
Load weights into base model#
[7]:
weights = torch.tensor(coef_df['coef'].tolist()).unsqueeze(0).float()
intercept = torch.tensor([intercept_value]).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': 'Tong, Huige, et al. "Cell-type-specific and '
'cell-type-independent DNA methylation clocks." Aging 16 (2024).',
'clock_name': 'hep',
'data_type': 'methylation',
'doi': 'https://doi.org/10.18632/aging.206184',
'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: ['cg02928345', 'cg05694089', 'cg06095777', 'cg06852461', 'cg10501210', 'cg15491247', 'cg26885220', 'cg21245277', 'cg25004441', 'cg03553786', 'cg04472001', 'cg10727673', 'cg11320499', 'cg14317285', 'cg17078152', 'cg11970349', 'cg04671476', 'cg08272151', 'cg09458096', 'cg11830096', 'cg14314729', 'cg16049690', 'cg26921969', 'cg05460965', 'cg13719443', 'cg14119792', 'cg09832613', 'cg10548492', 'cg10774647', 'cg14668632']... [Total elements: 70]
base_model_features: None
%==================================== Model Details ====================================%
Model Structure:
base_model: LinearModel(
(linear): Linear(in_features=70, out_features=1, bias=True)
)
%==================================== Model Details ====================================%
Model Parameters and Weights:
base_model.linear.weight: [-6.017436981201172, -5.4592413902282715, -2.176126003265381, -1.1635955572128296, -11.279679298400879, -2.4325146675109863, 0.5495437979698181, 34.79977798461914, 0.5566549301147461, 5.5801191329956055, -7.796560287475586, -7.169039249420166, 1.542575716972351, 15.734872817993164, 0.35905373096466064, 6.515843868255615, 19.468814849853516, 1.418412446975708, 0.03253895044326782, 3.5211238861083984, -0.3575636148452759, 3.376959800720215, 21.540037155151367, -7.9151692390441895, -2.348267078399658, -1.2504611015319824, -3.796130418777466, 13.8594388961792, 4.52095365524292, 0.2238227277994156]... [Tensor of shape torch.Size([1, 70])]
base_model.linear.bias: tensor([16.7101])
%==================================== 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([[103.2090],
[ 59.8991],
[ 7.7645],
[-52.8674],
[115.0976],
[-25.3601],
[148.0905],
[ 40.7066],
[104.7873],
[-31.2725]], 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: coefficients.csv