CamilloH3K36me3#
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
import joblib
import numpy as np
Instantiate model class#
[2]:
def print_entire_class(cls):
source = inspect.getsource(cls)
print(source)
print_entire_class(pya.models.CamilloH3K36me3)
class CamilloH3K36me3(pyagingModel):
def __init__(self):
super().__init__()
def preprocess(self, x):
return x
def postprocess(self, x):
return x
[3]:
model = pya.models.CamilloH3K36me3()
Define clock metadata#
[4]:
model.metadata["clock_name"] = "camilloh3k36me3"
model.metadata["data_type"] = "histone modification" # Paper: The study builds age predictors from seven histone modifications measured by ChIP-seq.
model.metadata["species"] = "Homo sapiens" # Paper: The analyzed ENCODE ChIP-seq data are from human tissues and cells.
model.metadata["year"] = 2025
model.metadata["approved_by_author"] = "✅"
model.metadata["citation"] = "de Lima Camillo, L. P., Asif, M. H., Horvath, S., Larschan, E., & Singh, R. Histone mark age of human tissues and cell types. Science Advances 11, eadk9373 (2025)."
model.metadata["doi"] = "https://doi.org/10.1126/sciadv.adk9373"
model.metadata["notes"] = "Pan-tissue chronological-age predictor trained on gene-level H3K36me3 ChIP-seq enrichment; ElasticNet feature selection is followed by truncated-SVD PCA and automatic relevance determination regression."
model.metadata["research_only"] = None
model.metadata["tissue"] = ["multi-tissue"] # Paper: The ENCODE collection contains 257 H3K36me3 ChIP-seq samples among 82 tissues and cell types.
model.metadata["predicts"] = ["chronological age"] # Paper: The H3K36me3 model is described as an age predictor.
model.metadata["training_target"] = ["chronological age"] # Paper: The training response is the ENCODE biosample age.
model.metadata["unit"] = ["years"] # Paper: The author tutorial reports predicted histone-mark age in years.
model.metadata["model_type"] = "PCA + elastic net + ARD regression" # Paper: ElasticNet selects nonzero features, PCA uses truncated SVD, and ARD regression makes the final prediction.
model.metadata["platform"] = ["ChIP-seq"] # Paper: The input consists of ENCODE histone-modification ChIP-seq enrichment tracks.
model.metadata["population"] = "all ages" # Paper: Samples span embryonic through 90-plus years and are roughly sex-balanced; cancer samples were removed for predictor evaluation.
model.metadata["journal"] = "Science Advances"
model.metadata["last_author"] = "Ritambhara Singh"
model.metadata["n_features"] = 870
model.metadata["citations"] = 4
model.metadata["citations_date"] = "2026-07-05"
Download clock dependencies#
Download GitHub repository#
[5]:
github_url = "https://github.com/rsinghlab/HistoneClocks.git"
github_folder_name = github_url.split('/')[-1].split('.')[0]
os.system(f"git clone {github_url}")
[5]:
0
Load features#
From CSV file#
[6]:
histone = 'H3K' + model.metadata["clock_name"].split('k')[1]
feature_selector_path = 'HistoneClocks/results/models/' + histone + '_feature_selector.pkl'
feature_selector = joblib.load(feature_selector_path)
dim_reduction_path = 'HistoneClocks/results/models/' + histone + '_dim_reduction.pkl'
dim_reduction = joblib.load(dim_reduction_path)
ard_model_path = 'HistoneClocks/results/models/' + histone + '_model.pkl'
ard_model = joblib.load(ard_model_path)
genes = pd.read_csv('HistoneClocks/metadata/Ensembl-105-EnsDb-for-Homo-sapiens-genes.csv')
chromosomes = ['1', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '2', '20', '21', '22', '3', '4', '5', '6', '7', '8', '9', 'X']
genes = genes[genes['chr'].apply(lambda x: x in chromosomes)]
genes.index = genes.gene_id
model.features = genes.gene_id[np.abs(feature_selector.coef_) > 0].tolist()
/Users/lucascamillo/mambaforge/envs/research/lib/python3.9/site-packages/sklearn/base.py:380: InconsistentVersionWarning: Trying to unpickle estimator ElasticNet from version 1.0.1 when using version 1.6.0. This might lead to breaking code or invalid results. Use at your own risk. For more info please refer to:
https://scikit-learn.org/stable/model_persistence.html#security-maintainability-limitations
warnings.warn(
/Users/lucascamillo/mambaforge/envs/research/lib/python3.9/site-packages/sklearn/base.py:380: InconsistentVersionWarning: Trying to unpickle estimator TruncatedSVD from version 1.0.1 when using version 1.6.0. This might lead to breaking code or invalid results. Use at your own risk. For more info please refer to:
https://scikit-learn.org/stable/model_persistence.html#security-maintainability-limitations
warnings.warn(
/Users/lucascamillo/mambaforge/envs/research/lib/python3.9/site-packages/sklearn/base.py:380: InconsistentVersionWarning: Trying to unpickle estimator ARDRegression from version 1.0.1 when using version 1.6.0. This might lead to breaking code or invalid results. Use at your own risk. For more info please refer to:
https://scikit-learn.org/stable/model_persistence.html#security-maintainability-limitations
warnings.warn(
Load weights into base model#
[7]:
weights = torch.tensor(ard_model.coef_).unsqueeze(0).float()
intercept = torch.tensor([ard_model.intercept_]).float()
rotation = torch.tensor(dim_reduction.components_.T).float()
center = torch.tensor(0)
PC linear model#
[8]:
base_model = pya.models.PCLinearModel(input_dim=len(model.features), pc_dim=rotation.shape[1])
base_model.center.data = center.float()
base_model.rotation.data = rotation.float()
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': 'de Lima Camillo, Lucas Paulo, et al. "Histone mark age of human '
'tissues and cells." Science Advances 11.1 (2025): eadk9373.',
'clock_name': 'camilloh3k36me3',
'data_type': 'histone mark',
'doi': 'https://doi.org/10.1126/sciadv.adk9373',
'notes': None,
'research_only': None,
'species': 'Homo sapiens',
'version': None,
'year': 2023}
reference_values: None
preprocess_name: None
preprocess_dependencies: None
postprocess_name: None
postprocess_dependencies: None
features: ['ENSG00000278267', 'ENSG00000223181', 'ENSG00000188976', 'ENSG00000187961', 'ENSG00000188157', 'LRG_198', 'ENSG00000242590', 'ENSG00000078808', 'ENSG00000278073', 'ENSG00000169972', 'ENSG00000284372', 'ENSG00000221978', 'ENSG00000242485', 'ENSG00000264293', 'ENSG00000268575', 'ENSG00000227775', 'ENSG00000067606', 'ENSG00000271806', 'ENSG00000182873', 'ENSG00000157881', 'ENSG00000157873', 'ENSG00000158109', 'ENSG00000116213', 'ENSG00000266075', 'ENSG00000169598', 'ENSG00000264341', 'ENSG00000264101', 'ENSG00000116237', 'ENSG00000215788', 'ENSG00000162408']... [Total elements: 870]
base_model_features: None
%==================================== Model Details ====================================%
Model Structure:
base_model: PCLinearModel(
(linear): Linear(in_features=256, out_features=1, bias=True)
)
%==================================== Model Details ====================================%
Model Parameters and Weights:
base_model.center: tensor(0.)
base_model.rotation: [0.02360893413424492, 0.036521051079034805, 0.04995967820286751, -0.013705668039619923, 0.007718259003013372, 0.014541537500917912, -0.009840598329901695, -0.016613848507404327, -0.035083089023828506, 0.0806567370891571, -0.008510556071996689, -0.07647418230772018, 0.061193931847810745, -0.10237399488687515, 0.008097291924059391, -0.01895865611732006, -0.08735031634569168, 0.02352394536137581, -0.029451260343194008, -0.08730751276016235, -0.014730032533407211, 9.406062599737197e-05, -0.10667144507169724, -0.04809011518955231, 0.011290607042610645, 0.05470702797174454, -0.020992428064346313, 0.07109186798334122, -0.01515013538300991, -0.05940837040543556]... [Tensor of shape torch.Size([870, 256])]
base_model.linear.weight: [0.0, -1.2875069379806519, -0.4023706018924713, -1.5389361381530762, -2.0026886463165283, -5.8203630447387695, 0.9255226254463196, 1.9064357280731201, 0.744470477104187, -3.327554225921631, 0.3793397843837738, -0.6767740845680237, -0.3410148322582245, 1.4468495845794678, 3.5321295261383057, 0.0, -0.5377044677734375, -0.4128347635269165, 0.5965965986251831, -2.0185458660125732, -1.553613305091858, -1.4146347045898438, 1.675315260887146, 0.35561496019363403, 1.2713336944580078, -0.8463054299354553, 0.21259747445583344, 0.28144025802612305, 0.9452900886535645, 0.6829139590263367]... [Tensor of shape torch.Size([1, 256])]
base_model.linear.bias: tensor([42.6736])
%==================================== 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([[53.7090],
[66.7885],
[38.7507],
[36.8688],
[55.5445],
[23.6183],
[41.5866],
[52.9507],
[44.0985],
[47.9645]], 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 folder: HistoneClocks