Petkovich#
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.Petkovich)
class Petkovich(pyagingModel):
def __init__(self):
super().__init__()
def preprocess(self, x):
return x
def postprocess(self, x):
"""
Applies a convertion from the output of an ElasticNet to mouse age in months.
"""
a = 0.1666
b = 0.4185
c = -1.712
age = ((x - c) / a) ** (1 / b)
age = age / 30.5 # days to months
return age
[3]:
model = pya.models.Petkovich()
Define clock metadata#
[4]:
model.metadata["clock_name"] = 'petkovich'
model.metadata["data_type"] = 'methylation'
model.metadata["species"] = 'Mus musculus'
model.metadata["year"] = 2017
model.metadata["approved_by_author"] = '⌛'
model.metadata["citation"] = "Petkovich, Daniel A., et al. \"Using DNA methylation profiling to evaluate biological age and longevity interventions.\" Cell metabolism 25.4 (2017): 954-960."
model.metadata["doi"] = "https://doi.org/10.1016/j.cmet.2017.03.016"
model.metadata["research_only"] = None
model.metadata["notes"] = None
Download clock dependencies#
Download directly with curl#
[5]:
supplementary_url = "https://elifesciences.org/download/aHR0cHM6Ly9jZG4uZWxpZmVzY2llbmNlcy5vcmcvYXJ0aWNsZXMvNDA2NzUvZWxpZmUtNDA2NzUtc3VwcDMtdjIueGxzeA--/elife-40675-supp3-v2.xlsx?_hash=qzOMc4yUFACfDFG%2FlgxkFTHWt%2BSXSmP9zz1BM3oOTRM%3D"
supplementary_file_name = "coefficients.xlsx"
os.system(f"curl -o {supplementary_file_name} {supplementary_url}")
[5]:
0
Load features#
From Excel file#
[6]:
df = pd.read_excel('coefficients.xlsx', sheet_name='Blood', nrows=90)
df['feature'] = df['Chromosome'].astype(str) + ':' + df['Position'].astype(int).astype(str)
df['coefficient'] = df['Weight']
model.features = df['feature'].tolist()
Load weights into base model#
[7]:
weights = torch.tensor(df['coefficient'].tolist()).unsqueeze(0)
intercept = torch.tensor([0.0])
Linear model#
[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 = 'petkovich'
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': 'Petkovich, Daniel A., et al. "Using DNA methylation profiling to '
'evaluate biological age and longevity interventions." Cell '
'metabolism 25.4 (2017): 954-960.',
'clock_name': 'petkovich',
'data_type': 'methylation',
'doi': 'https://doi.org/10.1016/j.cmet.2017.03.016',
'notes': None,
'research_only': None,
'species': 'Mus musculus',
'version': None,
'year': 2017}
reference_values: None
preprocess_name: None
preprocess_dependencies: None
postprocess_name: 'petkovich'
postprocess_dependencies: None
features: ['chr19:23893237', 'chr19:34746572', 'chr18:45589182', 'chr18:58836611', 'chr16:10502162', 'chr16:10502211', 'chr16:36990110', 'chr16:44812861', 'chr16:44812942', 'chr16:72663969', 'chr15:84756593', 'chr15:98780540', 'chr14:74978494', 'chr13:25850022', 'chr13:60687073', 'chr12:103214578', 'chr12:103214639', 'chr12:17993343', 'chr12:20196778', 'chr12:20196795', 'chr12:24252005', 'chr12:24252044', 'chr12:24252062', 'chr12:24252074', 'chr11:109011767', 'chr11:49978547', 'chr11:57832738', 'chr11:59283095', 'chr11:82930766', 'chr11:82930771']... [Total elements: 90]
base_model_features: None
%==================================== Model Details ====================================%
Model Structure:
base_model: LinearModel(
(linear): Linear(in_features=90, out_features=1, bias=True)
)
%==================================== Model Details ====================================%
Model Parameters and Weights:
base_model.linear.weight: [0.013973841443657875, -0.208111971616745, -0.052282609045505524, 0.09845656156539917, 0.2287983000278473, 0.041504427790641785, -0.12888140976428986, -0.1270751655101776, -0.11876147240400314, 0.07533302158117294, 0.006506402976810932, 0.02291547879576683, -0.015255635604262352, -0.04044732078909874, -0.028440294787287712, -0.009072709828615189, -0.1302095651626587, 0.13603146374225616, 0.0851239338517189, 0.0067262169905006886, 0.20910842716693878, 0.006870004814118147, 0.06277254968881607, 0.03797502815723419, 0.1745307892560959, -0.09591705352067947, 0.05482637137174606, -0.08698525279760361, 0.016051754355430603, 0.13305535912513733]... [Tensor of shape torch.Size([1, 90])]
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([[50.8075],
[27.5472],
[ 1.1953],
[ 6.6927],
[17.1703],
[24.9932],
[15.8308],
[ 1.1290],
[ 3.4376],
[ 0.0714]], dtype=torch.float64, grad_fn=<DivBackward0>)
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: coefficients.xlsx