CamilloPanHistone#
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.CamilloPanHistone)
class CamilloPanHistone(pyagingModel):
def __init__(self):
super().__init__()
def preprocess(self, x):
return x
def postprocess(self, x):
return x
[3]:
model = pya.models.CamilloPanHistone()
Define clock metadata#
[4]:
model.metadata["clock_name"] = 'camillopanhistone'
model.metadata["data_type"] = 'histone mark'
model.metadata["species"] = 'Homo sapiens'
model.metadata["year"] = 2025
model.metadata["approved_by_author"] = '✅'
model.metadata["citation"] = "de Lima Camillo, Lucas Paulo, et al. \"Histone mark age of human tissues and cell types.\" Science Advances 11.1 (2025): eadk9373."
model.metadata["doi"] = 'https://doi.org/10.1126/sciadv.adk9373'
model.metadata["research_only"] = None
model.metadata["notes"] = "Pan-tissue, pan-histone-mark age predictor that integrates ChIP-seq signal from multiple histone modifications across diverse human tissues, demonstrating that age is broadly encoded across the epigenome with accuracy comparable to DNA-methylation clocks."
model.metadata["tissue"] = 'multi-tissue (82 distinct human tissues; also validated on primary cell types)'
model.metadata["predicts"] = 'chronological age'
model.metadata["unit"] = 'years'
model.metadata["model_type"] = 'PCA + elastic net'
model.metadata["platform"] = 'ChIP-seq'
model.metadata["population"] = 'humans, pan-tissue, wide age range (embryonic to 90+ years)'
model.metadata["journal"] = 'Science Advances'
model.metadata["last_author"] = 'Ritambhara Singh'
model.metadata["n_features"] = 3739
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 = 'pan_histone'
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': 'camillopanhistone',
'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', 'ENSG00000279457', 'ENSG00000225880', 'ENSG00000187961', 'ENSG00000188290', 'ENSG00000187608', 'ENSG00000224969', 'LRG_1231', 'ENSG00000186827', 'LRG_1319', 'ENSG00000176022', 'LRG_1261', 'ENSG00000131584', 'ENSG00000278073', 'ENSG00000240731', 'ENSG00000224051', 'ENSG00000107404', 'ENSG00000284372', 'ENSG00000175756', 'ENSG00000221978', 'ENSG00000235098', 'ENSG00000225905', 'ENSG00000205116', 'ENSG00000225285', 'ENSG00000215014', 'ENSG00000274481', 'ENSG00000228594', 'ENSG00000197530', 'ENSG00000187730', 'ENSG00000162585']... [Total elements: 3739]
base_model_features: None
%==================================== Model Details ====================================%
Model Structure:
base_model: PCLinearModel(
(linear): Linear(in_features=1796, out_features=1, bias=True)
)
%==================================== Model Details ====================================%
Model Parameters and Weights:
base_model.center: tensor(0.)
base_model.rotation: [0.0018416275270283222, 0.014324158430099487, -0.010694649070501328, 0.012791091576218605, -0.005202800035476685, -0.0004988610162399709, -0.00938812829554081, 0.0028052637353539467, -0.00256216898560524, -0.002669402863830328, 0.007808406837284565, -0.010051244869828224, 0.0032627596519887447, 0.015527973882853985, -0.002606053138151765, -0.0011440989328548312, 0.0065333242528140545, 0.0014323854120448232, -0.008486825041472912, 0.0015797532396391034, -0.00933939591050148, 0.0004230770864523947, 0.0005480548716150224, -0.002184225944802165, 0.0017713935812935233, -0.011278705671429634, 0.013966028578579426, -0.008065817877650261, 0.017902590334415436, 0.0007606155704706907]... [Tensor of shape torch.Size([3739, 1796])]
base_model.linear.weight: [0.06349078565835953, -0.06451046466827393, 0.07253015786409378, -0.05508815869688988, 0.03403407335281372, 0.8896585702896118, -0.2548756003379822, -0.1410745233297348, 0.35230737924575806, 0.45682480931282043, -1.0241423845291138, 0.7528742551803589, 0.02878468669950962, -1.7732597589492798, 0.0, -0.7164396643638611, 1.5336309671401978, -1.417890191078186, 1.157829761505127, -1.9165352582931519, -1.3991321325302124, -0.8890577554702759, 0.07125996053218842, -1.4806439876556396, -0.09198015928268433, 0.23787471652030945, -1.5816597938537598, 0.6791732907295227, 0.19982701539993286, -1.6992993354797363]... [Tensor of shape torch.Size([1, 1796])]
base_model.linear.bias: tensor([44.8891])
%==================================== 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([[ 32.6708],
[ 53.1045],
[ 49.2967],
[ 37.4920],
[ 9.0331],
[-23.4749],
[ 32.2671],
[ 43.1352],
[ 24.3412],
[ 21.3409]], 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