DNAmStress#
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.DNAmStress)
class DNAmStress(LinearReferenceClock):
pass
[3]:
model = pya.models.DNAmStress()
Define clock metadata#
[4]:
model.metadata["clock_name"] = 'dnamstress'
model.metadata["data_type"] = 'methylation'
model.metadata["species"] = 'Homo sapiens'
model.metadata["year"] = 2023
model.metadata["approved_by_author"] = '⌛'
model.metadata["citation"] = "Jung, Sun Jae, et al. \"An epigenetic biomarker of stress and its association with cardiovascular disease.\" Biological Psychiatry 93.4 (2023): 331-341."
model.metadata["doi"] = "https://doi.org/10.1016/j.biopsych.2022.06.036"
model.metadata["research_only"] = None
model.metadata["notes"] = "Blood methylation score of cumulative stress comprising 211 CpGs selected by penalised regression as a proxy for a composite of stress-related exposures. Associates with accelerated epigenetic aging, shortened methylation-based telomere length and cardiovascular disease."
model.metadata["tissue"] = 'whole blood'
model.metadata["predicts"] = 'stress exposure (composite/cumulative stress score, "MS_stress")'
model.metadata["unit"] = 'score (arbitrary)'
model.metadata["model_type"] = 'Elastic net'
model.metadata["platform"] = 'Illumina 450K/EPIC'
model.metadata["population"] = 'adults (alcohol use disorder patients and controls, n=615; replicated in Generation Scotland and Grady Trauma Project cohorts)'
model.metadata["journal"] = 'Biological Psychiatry'
model.metadata["last_author"] = 'Falk W. Lohoff'
model.metadata["n_features"] = 211
model.metadata["citations"] = 27
model.metadata["citations_date"] = '2026-07-05'
Download clock dependencies#
[5]:
os.system(f"curl -sL -o DNAmStress_CpGs.rda https://raw.githubusercontent.com/HigginsChenLab/methylCIPHER/19b12296b0d7eb7055a97d068064df635f44ce3e/data/DNAmStress_CpGs.rda")
os.system(f"curl -sL -o DNAmStress_ref.rda https://raw.githubusercontent.com/HigginsChenLab/methylCIPHER/19b12296b0d7eb7055a97d068064df635f44ce3e/data/DNAmStress_ref.rda")
[5]:
0
[6]:
%%writefile download.r
library(jsonlite)
load("DNAmStress_CpGs.rda")
load("DNAmStress_ref.rda")
write_json(DNAmStress_CpGs, "coefficients.json", digits = 10)
write_json(DNAmStress_ref$intercept, "intercept.json", digits = 10)
Writing download.r
[7]:
os.system("Rscript download.r")
[7]:
0
Load features#
[8]:
coef_df = pd.DataFrame(json.load(open('coefficients.json')))
model.features = coef_df['CpG'].tolist()
iv = json.load(open('intercept.json'))
intercept_value = iv[0] if isinstance(iv, list) else iv
Load weights into base model#
[9]:
weights = torch.tensor(coef_df['coefficient'].tolist()).unsqueeze(0).float()
intercept = torch.tensor([intercept_value]).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 = None
Load preprocess and postprocess objects#
[12]:
model.preprocess_name = None
model.preprocess_dependencies = None
[13]:
model.postprocess_name = None
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': 'Jung, Sun Jae, et al. "An epigenetic biomarker of stress and its '
'association with cardiovascular disease." Biological Psychiatry '
'93.4 (2023): 331-341.',
'clock_name': 'dnamstress',
'data_type': 'methylation',
'doi': 'https://doi.org/10.1016/j.biopsych.2022.06.036',
'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: ['cg00188055', 'cg00418087', 'cg00452133', 'cg00599628', 'cg00684116', 'cg00728602', 'cg01047613', 'cg01085421', 'cg01245530', 'cg01607512', 'cg01631065', 'cg02107357', 'cg02386470', 'cg02606284', 'cg02606535', 'cg02607810', 'cg02652698', 'cg02873991', 'cg02978227', 'cg03104567', 'cg03120234', 'cg03221779', 'cg03579303', 'cg03581822', 'cg03626783', 'cg03642635', 'cg03693374', 'cg03723497', 'cg03744383', 'cg04048370']... [Total elements: 211]
base_model_features: None
%==================================== Model Details ====================================%
Model Structure:
base_model: LinearModel(
(linear): Linear(in_features=211, out_features=1, bias=True)
)
%==================================== Model Details ====================================%
Model Parameters and Weights:
base_model.linear.weight: [1.7692569494247437, 5.452592849731445, 0.36093270778656006, 0.04217686131596565, -0.0875726118683815, -0.1617601066827774, -2.8009119033813477, -0.0006456300034187734, 2.6688179969787598, 1.0967479944229126, 2.873945951461792, 0.3544867932796478, -2.170973062515259, 2.942610025405884, 4.0788421630859375, -0.08575636893510818, 0.3709535002708435, 0.18792760372161865, -4.1162872314453125, -0.25866061449050903, 5.40001916885376, -2.2270829677581787, -0.7070323824882507, 1.7177339792251587, -0.6149824857711792, 0.26971670985221863, -1.411486029624939, 1.3798350095748901, -0.12567970156669617, 1.3220950365066528]... [Tensor of shape torch.Size([1, 211])]
base_model.linear.bias: tensor([-4.4941])
%==================================== 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([[-33.9411],
[-62.7000],
[ 93.3530],
[ 14.1386],
[-18.2623],
[ 4.9429],
[ 94.5241],
[ 63.0782],
[ 4.6987],
[ 66.1088]], dtype=torch.float64, grad_fn=<AddmmBackward0>)
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: intercept.json
Deleted file: DNAmStress_CpGs.rda
Deleted file: download.r
Deleted file: coefficients.json
Deleted file: DNAmStress_ref.rda