CorticalClock#

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

Instantiate model class#

[2]:
def print_entire_class(cls):
    source = inspect.getsource(cls)
    print(source)

print_entire_class(pya.models.CorticalClock)
class CorticalClock(LinearReferenceClock):
    def postprocess(self, x):
        """Horvath anti-logarithmic linear transformation (adult age = 20)."""
        adult_age = 20
        mask_negative = x < 0
        mask_non_negative = ~mask_negative
        age = torch.empty_like(x)
        age[mask_negative] = (1 + adult_age) * torch.exp(x[mask_negative]) - 1
        age[mask_non_negative] = (1 + adult_age) * x[mask_non_negative] + adult_age
        return age

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

Define clock metadata#

[4]:
model.metadata["clock_name"] = "corticalclock"
model.metadata["data_type"] = "DNA methylation"  # Paper: methylation
model.metadata["species"] = "Homo sapiens"  # Paper: Homo sapiens
model.metadata["year"] = 2020
model.metadata["approved_by_author"] = "⌛"
model.metadata["citation"] = "Shireby, G. L., et al. \"Recalibrating the epigenetic clock: implications for assessing biological age in the human cortex.\" Brain 143.12 (2020): 3763-3775."
model.metadata["doi"] = "https://doi.org/10.1093/brain/awaa334"
model.metadata["notes"] = "Cortex-specific DNA-methylation chronological-age estimator trained by elastic net on 1,047 post-mortem cortical samples; its 347-CpG weighted score is back-transformed to years."
model.metadata["research_only"] = None
model.metadata["tissue"] = ["brain cortex"]  # Paper: brain cortex (post-mortem human cortical tissue)
model.metadata["predicts"] = ["chronological age"]  # Paper: chronological age
model.metadata["training_target"] = ["chronological age"]  # Paper: chronological age
model.metadata["unit"] = ["years"]  # Paper: years
model.metadata["model_type"] = "elastic net regression"  # Paper: Elastic net
model.metadata["platform"] = ["Illumina 450K"]  # Paper: Illumina 450K
model.metadata["population"] = "human, age unspecified"  # Paper: human cortex training set: 1,047 samples from 832 donors, ages 1–108 years
model.metadata["journal"] = "Brain"
model.metadata["last_author"] = "Jonathan Mill"
model.metadata["n_features"] = 347
model.metadata["citations"] = 206
model.metadata["citations_date"] = "2026-07-05"

Download clock dependencies#

[5]:
os.system(f"curl -sL -o CorticalClockCoefs.txt https://raw.githubusercontent.com/gemmashireby/CorticalClock/80c3df19c01d9aac25c9fd5aecd5bbc42aba0939/PredCorticalAge/CorticalClockCoefs.txt")
os.system(f"curl -sL -o Ref_DNAm_brain_values.rdat https://raw.githubusercontent.com/gemmashireby/CorticalClock/80c3df19c01d9aac25c9fd5aecd5bbc42aba0939/PredCorticalAge/Ref_DNAm_brain_values.rdat")
[5]:
0
[6]:
%%writefile download.r

library(jsonlite)
coefs <- read.table("CorticalClockCoefs.txt", header = TRUE, stringsAsFactors = FALSE)
coefs <- coefs[tolower(coefs$probe) != "intercept" & tolower(coefs$probe) != "(intercept)", ]
load("Ref_DNAm_brain_values.rdat")
refvals <- as.numeric(ref[coefs$probe])
write_json(list(probe = coefs$probe, coef = coefs$coef, ref = refvals), "cortical.json", digits = 10)
Writing download.r
[7]:
os.system("Rscript download.r")
[7]:
0

Load features#

[8]:
d = json.load(open('cortical.json'))
model.features = list(d['probe'])

Load weights into base model#

[9]:
# Intercept 0.577682570446177 hard-coded in the CorticalClock reference script
weights = torch.tensor(d['coef']).unsqueeze(0).float()
intercept = torch.tensor([0.577682570446177]).float()
[10]:
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#

[11]:
model.reference_values = d['ref']

Load preprocess and postprocess objects#

[12]:
model.preprocess_name = None
model.preprocess_dependencies = None
[13]:
model.postprocess_name = 'anti_log_linear'
model.postprocess_dependencies = None

Check all clock parameters#

[14]:
pya.utils.print_model_details(model)

%==================================== Model Details ====================================%
Model Attributes:

training: True
metadata: {'approved_by_author': '⌛',
 'citation': 'Shireby, Gemma L., et al. "Recalibrating the epigenetic clock: '
             'implications for assessing biological age in the human cortex." '
             'Brain 143.12 (2020): 3763-3775.',
 'clock_name': 'corticalclock',
 'data_type': 'methylation',
 'doi': 'https://doi.org/10.1093/brain/awaa334',
 'notes': None,
 'research_only': None,
 'species': 'Homo sapiens',
 'version': None,
 'year': 2020}
reference_values: [0.21611617687, 0.15740657645, 0.7341710846, 0.060822631032, 0.10575749654, 0.62440019335, 0.13956151931, 0.93910437046, 0.67922573527, 0.41269620156, 0.18058134103, 0.30387161589, 0.72916401957, 0.16249365613, 0.10514838761, 0.32006057604, 0.41533755409, 0.76224987996, 0.1012865392, 0.068627506888, 0.62711858238, 0.067610974155, 0.73657937789, 0.085680987307, 0.16091221649, 0.5857097145, 0.65691321067, 0.5219473048, 0.14838958913, 0.46603381304]... [Total elements: 347]
preprocess_name: None
preprocess_dependencies: None
postprocess_name: 'anti_log_linear'
postprocess_dependencies: None
features: ['cg00059225', 'cg00088042', 'cg00252534', 'cg00297950', 'cg00384539', 'cg00491255', 'cg00521255', 'cg00648582', 'cg00771642', 'cg00924265', 'cg00935119', 'cg00940577', 'cg01091514', 'cg01122755', 'cg01162920', 'cg01194538', 'cg01264729', 'cg01311102', 'cg01529637', 'cg01532168', 'cg01616394', 'cg01639032', 'cg01641432', 'cg01655150', 'cg01745370', 'cg01899542', 'cg02046143', 'cg02047661', 'cg02357838', 'cg02361903']... [Total elements: 347]
base_model_features: None

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

base_model: LinearModel(
  (linear): Linear(in_features=347, out_features=1, bias=True)
)

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

base_model.linear.weight: [0.24595920741558075, 0.18271556496620178, 0.16822335124015808, 0.14175772666931152, 0.17820188403129578, 0.14450779557228088, -0.2443627119064331, -0.03914619982242584, 0.1277257353067398, -0.06851626932621002, -0.038119036704301834, -0.061217304319143295, -0.03222978115081787, 0.06571090221405029, -0.1973567008972168, -0.151609405875206, -0.15242373943328857, -0.10921627283096313, 0.026809634640812874, 0.3346559405326843, -0.01871008612215519, 0.5150526762008667, -0.0013768351636826992, -0.32761350274086, -0.00586429750546813, -0.050962597131729126, -0.007779109291732311, -0.017116934061050415, 0.2379734218120575, -0.5452234148979187]... [Tensor of shape torch.Size([1, 347])]
base_model.linear.bias: tensor([0.5777])

%==================================== Model Details ====================================%

Basic test#

[15]:
torch.manual_seed(42)
input = torch.randn(10, len(model.features), dtype=float)
model.eval()
model.to(float)
pred = model(input)
pred
[15]:
tensor([[ 2.8786e+01],
        [-9.7972e-01],
        [ 1.7019e+01],
        [-9.1772e-01],
        [ 8.8761e+00],
        [ 1.7652e+01],
        [ 1.6345e+02],
        [-2.4936e-03],
        [-9.7389e-01],
        [-9.8054e-01]], dtype=torch.float64, grad_fn=<IndexPutBackward0>)

Save torch model#

[16]:
torch.save(model, f"../weights/{model.metadata['clock_name']}.pt")

Clear directory#

[17]:
# 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: CorticalClockCoefs.txt
Deleted file: Ref_DNAm_brain_values.rdat
Deleted file: download.r
Deleted file: cortical.json