McCartneyAlcohol#
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.McCartneyAlcohol)
class McCartneyAlcohol(pyagingModel):
def __init__(self):
super().__init__()
def preprocess(self, x):
if self.reference_values is None:
return x
if isinstance(self.reference_values, torch.Tensor):
reference = self.reference_values.to(device=x.device, dtype=x.dtype)
else:
reference = torch.tensor(self.reference_values, device=x.device, dtype=x.dtype)
return torch.where(torch.isnan(x), reference, x)
def postprocess(self, x):
return x
[3]:
model = pya.models.McCartneyAlcohol()
Define clock metadata#
[4]:
model.metadata["clock_name"] = 'mccartneyalcohol'
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 alcohol consumption, one of ten lifestyle and health scores trained on Illumina array data in the large Generation Scotland cohort and tested out-of-sample. Alcohol was among the scores associated with all-cause mortality."
model.metadata["tissue"] = 'whole blood'
model.metadata["predicts"] = 'alcohol consumption'
model.metadata["unit"] = 'weeks'
model.metadata["model_type"] = 'Elastic net'
model.metadata["platform"] = 'Illumina 450K'
model.metadata["population"] = 'adults (Generation Scotland cohort, n=5087)'
model.metadata["journal"] = 'Genome biology'
model.metadata["last_author"] = 'Riccardo E. Marioni'
model.metadata["n_features"] = 450
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 S3 - Alcohol (McCartney et al. 2018)
coef_df = pd.read_excel('mccartney_predictors.xlsx', sheet_name='Table S3 - Alcohol')
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': 'mccartneyalcohol',
'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: ['cg16113793', 'cg15970375', 'cg16057915', 'cg01503881', 'cg02650017', 'cg08174504', 'cg19613400', 'cg15537269', 'cg08033031', 'cg27078522', 'cg15804767', 'cg27118035', 'cg03440556', 'cg05926784', 'cg24011637', 'cg25215890', 'cg16298547', 'cg05322916', 'cg10785793', 'cg15348839', 'cg20060185', 'cg10747118', 'cg02402946', 'cg00107782', 'cg17301216', 'cg22857025', 'cg27020362', 'cg26516004', 'cg21376883', 'cg13215995']... [Total elements: 450]
base_model_features: None
%==================================== Model Details ====================================%
Model Structure:
base_model: LinearModel(
(linear): Linear(in_features=450, out_features=1, bias=True)
)
%==================================== Model Details ====================================%
Model Parameters and Weights:
base_model.linear.weight: [3.862548351287842, 2.5282623767852783, 2.1660773754119873, 1.7681397199630737, 1.6551880836486816, 1.3851169347763062, 1.1948226690292358, 1.0830217599868774, 0.9930517077445984, 0.9852260947227478, 0.9295053482055664, 0.9087173342704773, 0.7987855672836304, 0.7958981990814209, 0.7665864825248718, 0.7589118480682373, 0.7468999624252319, 0.6992080807685852, 0.6736985445022583, 0.6460532546043396, 0.6401790380477905, 0.6225373148918152, 0.5754739046096802, 0.5703202486038208, 0.5235690474510193, 0.5012584924697876, 0.4931233823299408, 0.49302104115486145, 0.49224457144737244, 0.48730146884918213]... [Tensor of shape torch.Size([1, 450])]
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([[ 2.0260],
[ -7.1355],
[ 13.1317],
[ 23.1027],
[ 8.5896],
[ 17.2480],
[ 7.9061],
[-11.0824],
[ -4.6274],
[ -4.5061]], 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