CTSLiver#
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.CTSLiver)
class CTSLiver(LinearReferenceClock):
pass
[3]:
model = pya.models.CTSLiver()
Define clock metadata#
[4]:
model.metadata["clock_name"] = "ctsliver"
model.metadata["data_type"] = "DNA methylation" # Paper: The model is based on DNA methylation measurements.
model.metadata["species"] = "Homo sapiens" # Paper: The study samples are Homo sapiens.
model.metadata["year"] = 2024
model.metadata["approved_by_author"] = "⌛"
model.metadata["citation"] = "Tong, Huige, et al. \"Cell-type specific epigenetic clocks to quantify biological age at cell-type resolution.\" Aging 16 (2024): 14204–14237."
model.metadata["doi"] = "https://doi.org/10.18632/aging.206184"
model.metadata["notes"] = "LiverClock is a liver tissue-specific chronological-age clock trained by lasso on age-associated CpGs identified after adjustment for five estimated liver cell fractions; unlike HepClock, it is not hepatocyte-specific."
model.metadata["research_only"] = None
model.metadata["tissue"] = ["liver"] # Paper: The listed tissue is the model-development sample material.
model.metadata["predicts"] = ["chronological age"] # Paper: The reported predictor output is chronological age.
model.metadata["training_target"] = ["chronological age"] # Paper: The fitting outcome is chronological age.
model.metadata["unit"] = ["years"] # Paper: The returned construct is expressed as years.
model.metadata["model_type"] = "LASSO regression" # Paper: The clock was fitted using LASSO.
model.metadata["platform"] = ["Illumina EPIC"] # Paper: Training/selection used Illumina EPIC.
model.metadata["population"] = "adults" # Paper: adults aged 18–75 years (210 normal liver samples)
model.metadata["journal"] = "Aging"
model.metadata["last_author"] = "Andrew E. Teschendorff"
model.metadata["n_features"] = 90
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/Liver.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': 'ctsliver',
'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: ['cg00147307', 'cg04055835', 'cg07014827', 'cg08639762', 'cg09085216', 'cg10501210', 'cg11037818', 'cg11837471', 'cg19861048', 'cg22793142', 'cg27553626', 'cg01139016', 'cg03602360', 'cg03957108', 'cg11797365', 'cg12477533', 'cg23059946', 'cg26469895', 'cg00481951', 'cg01633093', 'cg17631451', 'cg20669012', 'cg24572745', 'cg02650266', 'cg15848147', 'cg27652893', 'cg04671476', 'cg16049690', 'cg01017235', 'cg16867657']... [Total elements: 90]
base_model_features: None
%==================================== Model Details ====================================%
Model Structure:
base_model: LinearModel(
(linear): Linear(in_features=90, out_features=1, bias=True)
)
%==================================== Model Details ====================================%
Model Parameters and Weights:
base_model.linear.weight: [0.06677141785621643, -0.4691475033760071, 8.956233978271484, -7.425961494445801, -0.37923702597618103, -0.9674519896507263, -0.2163476198911667, -0.6666942834854126, -0.0633813887834549, -11.506742477416992, -4.447482585906982, -0.7794511914253235, 1.741921067237854, 3.4112987518310547, 1.951097846031189, 4.32723331451416, -7.400779724121094, -0.8474096059799194, 1.4585193395614624, -2.9431684017181396, -0.044251661747694016, -2.712244987487793, -3.016547918319702, 1.0454469919204712, 0.705701470375061, -5.014070510864258, 2.0638656616210938, 0.18794922530651093, 1.635787010192871, 51.198280334472656]... [Tensor of shape torch.Size([1, 90])]
base_model.linear.bias: tensor([48.3286])
%==================================== 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([[140.2069],
[ 45.0042],
[ -4.2454],
[-15.0873],
[-27.0882],
[150.2301],
[ 29.9997],
[257.3345],
[ 42.9376],
[-70.8377]], 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