CamilloH3K9ac#

Index#

  1. Instantiate model class

  2. Define clock metadata

  3. Download clock dependencies

  4. Load features

  5. Load weights into base model

  6. Load reference values

  7. Load preprocess and postprocess objects

  8. Check all clock parameters

  9. Basic test

  10. Save torch model

  11. Clear directory

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.CamilloH3K9ac)
class CamilloH3K9ac(pyagingModel):
    def __init__(self):
        super().__init__()

    def preprocess(self, x):
        return x

    def postprocess(self, x):
        return x

[3]:
model = pya.models.CamilloH3K9ac()

Define clock metadata#

[4]:
model.metadata["clock_name"] = 'camilloh3k9ac'
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"] = "Chronological-age predictor built with a deep neural network from genome-wide H3K9ac ChIP-seq signal, a mark of active promoters, as part of a pan-tissue family of histone-mark aging clocks spanning human tissues and cell types."
model.metadata["tissue"] = 'Multi-tissue (human tissues and cell types; ENCODE ChIP-seq)'
model.metadata["predicts"] = 'chronological age'
model.metadata["unit"] = 'years'
model.metadata["model_type"] = 'PCA + elastic net'
model.metadata["platform"] = 'ChIP-seq'
model.metadata["population"] = 'Pan-age humans (fetal/embryonic to elderly)'
model.metadata["journal"] = 'Science Advances'
model.metadata["last_author"] = 'Ritambhara Singh'
model.metadata["n_features"] = 102
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': 'camilloh3k9ac',
 '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: ['ENSG00000248527', 'ENSG00000199347', 'ENSG00000117318', 'ENSG00000229167', 'ENSG00000288772', 'ENSG00000207340', 'ENSG00000264553', 'ENSG00000289288', 'ENSG00000250734', 'ENSG00000238279', 'ENSG00000208024', 'ENSG00000260021', 'ENSG00000288925', 'ENSG00000159388', 'ENSG00000289071', 'ENSG00000251508', 'ENSG00000289239', 'ENSG00000277563', 'ENSG00000169740', 'ENSG00000165644', 'ENSG00000138135', 'ENSG00000166189', 'LRG_564', 'ENSG00000107872', 'ENSG00000284525', 'ENSG00000284416', 'ENSG00000277846', 'ENSG00000278144', 'ENSG00000278050', 'ENSG00000289259']... [Total elements: 102]
base_model_features: None

%==================================== Model Details ====================================%
Model Structure:

base_model: PCLinearModel(
  (linear): Linear(in_features=35, out_features=1, bias=True)
)

%==================================== Model Details ====================================%
Model Parameters and Weights:

base_model.center: tensor(0.)
base_model.rotation: [0.026688871905207634, 0.00612650578841567, -0.023084469139575958, 0.09400180727243423, 0.0344255156815052, -0.07693058252334595, -0.014118839055299759, -0.1297181099653244, -0.06002800166606903, 0.014447161927819252, 0.09382186830043793, 0.003466519992798567, -0.15866149961948395, 0.028640473261475563, 0.06944424659013748, 0.2053719162940979, -0.13362054526805878, 0.04413615167140961, -0.14294372498989105, -0.011215132661163807, 0.039818428456783295, 0.08284883946180344, -0.0022151051089167595, -0.13009993731975555, 0.020843902602791786, 0.05471724271774292, -0.11845099180936813, 0.22964397072792053, -0.12406716495752335, -0.26873892545700073]... [Tensor of shape torch.Size([102, 35])]
base_model.linear.weight: [0.564490795135498, 4.7954535484313965, -4.093379497528076, 3.29366135597229, 0.0, -3.5194101333618164, 0.4891869127750397, -2.677807569503784, -0.44870513677597046, 1.55893874168396, 0.6157783269882202, 0.8828743100166321, 0.9632635116577148, -1.1242079734802246, -0.101211778819561, -0.5177064538002014, -2.407639980316162, -0.8229461312294006, 0.3041236400604248, -0.2354177087545395, -0.8482727408409119, -0.29311403632164, -0.33054083585739136, 0.8425723910331726, -1.0014386177062988, -1.3361852169036865, 0.0, -0.4254952669143677, 0.34747055172920227, -0.4351760447025299]... [Tensor of shape torch.Size([1, 35])]
base_model.linear.bias: tensor([43.8619])

%==================================== 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([[51.9300],
        [52.0249],
        [49.4161],
        [38.6956],
        [38.3531],
        [38.3666],
        [33.3411],
        [47.8231],
        [33.7270],
        [67.7895]], 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