McCartneyWHR#
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.McCartneyWHR)
class McCartneyWHR(LinearReferenceClock):
pass
[3]:
model = pya.models.McCartneyWHR()
Define clock metadata#
[4]:
model.metadata["clock_name"] = 'mccartneywhr'
model.metadata["data_type"] = 'methylation'
model.metadata["species"] = 'Homo sapiens'
model.metadata["year"] = 2018
model.metadata["approved_by_author"] = '⌛'
model.metadata["citation"] = "McCartney, Daniel L., et al. \"Epigenetic prediction of complex traits and death.\" Genome biology 19.1 (2018): 136."
model.metadata["doi"] = "https://doi.org/10.1186/s13059-018-1514-1"
model.metadata["research_only"] = None
model.metadata["notes"] = "Blood DNA-methylation LASSO predictor of waist-to-hip ratio, one of ten lifestyle and health scores trained on array methylation in the Generation Scotland cohort. Waist-to-hip ratio was among the scores that predicted all-cause mortality."
model.metadata["tissue"] = 'whole blood'
model.metadata["predicts"] = 'waist-to-hip ratio'
model.metadata["unit"] = 'score (arbitrary)'
model.metadata["model_type"] = 'LASSO'
model.metadata["platform"] = 'Illumina 450K/EPIC'
model.metadata["population"] = 'adults (Generation Scotland training cohort, mean age ~49; tested in Lothian Birth Cohort 1936, age ~70)'
model.metadata["journal"] = 'Genome biology'
model.metadata["last_author"] = 'Riccardo E. Marioni'
model.metadata["n_features"] = 226
model.metadata["citations"] = 301
model.metadata["citations_date"] = '2026-07-05'
Download clock dependencies#
[5]:
supplementary_url = "https://static-content.springer.com/esm/art%3A10.1186%2Fs13059-018-1514-1/MediaObjects/13059_2018_1514_MOESM1_ESM.xlsx"
supplementary_file_name = "mccartney_predictors.xlsx"
os.system(f"curl -sL -o {supplementary_file_name} {supplementary_url}")
[5]:
0
Load features#
[6]:
# Additional file 1, Table S9 - Waist-to-Hip ratio (McCartney et al. 2018)
coef_df = pd.read_excel('mccartney_predictors.xlsx', sheet_name='Table S9 - Waist-to-Hip ratio')
model.features = coef_df['CpG'].tolist()
Load weights into base model#
[7]:
# The penalised (LASSO) predictor has no intercept term
weights = torch.tensor(coef_df['Beta'].tolist()).unsqueeze(0).float()
intercept = torch.tensor([0.0]).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': 'McCartney, Daniel L., et al. "Epigenetic prediction of complex '
'traits and death." Genome biology 19.1 (2018): 136.',
'clock_name': 'mccartneywhr',
'data_type': 'methylation',
'doi': 'https://doi.org/10.1186/s13059-018-1514-1',
'notes': None,
'research_only': None,
'species': 'Homo sapiens',
'version': None,
'year': 2018}
reference_values: None
preprocess_name: None
preprocess_dependencies: None
postprocess_name: None
postprocess_dependencies: None
features: ['cg03005261', 'cg21637050', 'cg16728516', 'cg14267725', 'cg06500161', 'cg04804648', 'cg18909879', 'cg25921813', 'cg21020089', 'cg16284674', 'cg15092239', 'cg07769588', 'cg07215298', 'cg09249494', 'cg10474597', 'cg11832534', 'cg25110523', 'cg04453364', 'cg19519737', 'cg18515624', 'cg18054578', 'cg18011760', 'cg08563994', 'cg01616956', 'cg02079413', 'cg06192883', 'cg15132749', 'cg22669566', 'cg25349939', 'cg04816311']... [Total elements: 226]
base_model_features: None
%==================================== Model Details ====================================%
Model Structure:
base_model: LinearModel(
(linear): Linear(in_features=226, out_features=1, bias=True)
)
%==================================== Model Details ====================================%
Model Parameters and Weights:
base_model.linear.weight: [0.47226133942604065, 0.2731764614582062, 0.23187954723834991, 0.20890694856643677, 0.18225495517253876, 0.12761914730072021, 0.08936703205108643, 0.08627176284790039, 0.0851999968290329, 0.07440463453531265, 0.061605945229530334, 0.05795585736632347, 0.053718939423561096, 0.05213217809796333, 0.05174638330936432, 0.04884398728609085, 0.04772736132144928, 0.046122852712869644, 0.04307003319263458, 0.04154041036963463, 0.03536680340766907, 0.03154837712645531, 0.030331037938594818, 0.029633039608597755, 0.02755829133093357, 0.026697693392634392, 0.02443346194922924, 0.023988846689462662, 0.023213393986225128, 0.02202027104794979]... [Tensor of shape torch.Size([1, 226])]
base_model.linear.bias: tensor([0.])
%==================================== 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([[ 0.9362],
[ 1.4919],
[ 0.3194],
[-0.1748],
[ 0.6122],
[ 0.8324],
[-0.0945],
[-0.4978],
[ 1.0881],
[-0.8827]], 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: mccartney_predictors.xlsx