MammalianSkin3#
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
import numpy as np
Instantiate model class#
[2]:
def print_entire_class(cls):
source = inspect.getsource(cls)
print(source)
print_entire_class(pya.models.MammalianSkin3)
class MammalianSkin3(pyagingModel):
def __init__(self):
super().__init__()
def forward(self, x):
x_cpg = x[:, :-1707] # number of species in lookup table
x_species = x[:, -1707:] # number of species in lookup table
x = self.base_model(x_cpg)
x = self.postprocess(x, x_species)
return x
def preprocess(self, x):
return x
def postprocess(self, x, x_species):
"""
Converts output of to units of years.
"""
indices = torch.argmax(x_species, dim=1)
anage_array = self.postprocess_dependencies[0]
anage_tensor = torch.tensor(anage_array, dtype=x.dtype, device=x.device)
gestation_time = anage_tensor[indices, 0].unsqueeze(1)
average_maturity_age = anage_tensor[indices, 1].unsqueeze(1)
m_hat = 5 * (gestation_time / average_maturity_age) ** (0.38)
# Create a mask for negative and non-negative values
mask_negative = x < 0
mask_non_negative = ~mask_negative
x_pos = x[mask_non_negative]
x_neg = x[mask_negative]
gestation_time_pos = gestation_time[mask_non_negative]
gestation_time_neg = gestation_time[mask_negative]
average_maturity_age_pos = average_maturity_age[mask_non_negative]
average_maturity_age_neg = average_maturity_age[mask_negative]
m_hat_pos = m_hat[mask_non_negative]
m_hat_neg = m_hat[mask_negative]
# Initialize the result tensor
age_tensor = torch.empty_like(x)
# Exponential transformation for negative values
age_tensor[mask_non_negative] = (
m_hat_pos * (average_maturity_age_pos + gestation_time_pos) * (x_pos + 1) - gestation_time_pos
)
# Linear transformation for non-negative values
age_tensor[mask_negative] = (
m_hat_neg * (average_maturity_age_neg + gestation_time_neg) * torch.exp(x_neg) - gestation_time_neg
)
return age_tensor
[3]:
model = pya.models.MammalianSkin3()
Define clock metadata#
[4]:
model.metadata["clock_name"] = 'mammalianskin3'
model.metadata["data_type"] = 'methylation'
model.metadata["species"] = 'multi'
model.metadata["year"] = 2023
model.metadata["approved_by_author"] = '⌛'
model.metadata["citation"] = "Lu, A. T., et al. \"Universal DNA methylation age across mammalian tissues.\" Nature aging 3.9 (2023): 1144-1166."
model.metadata["doi"] = "https://doi.org/10.1038/s43587-023-00462-6"
model.metadata["research_only"] = None
model.metadata["notes"] = None
Download clock dependencies#
Download GitHub repository#
[5]:
github_url = "https://github.com/shorvath/MammalianMethylationConsortium.git"
github_folder_name = github_url.split('/')[-1].split('.')[0]
os.system(f"git clone {github_url}")
[5]:
0
Download from R package#
[6]:
%%writefile download.r
options(repos = c(CRAN = "https://cloud.r-project.org/"))
myinput.list=readRDS('MammalianMethylationConsortium/UniversalPanMammalianClock/ClockParameters/mydata_GitHub.Rds')
anage=myinput.list[[3]]
anage=subset(anage,select=c(SpeciesLatinName,GestationTimeInYears, averagedMaturity.yrs,maxAge))
anage$HighmaxAge=1.3*anage$maxAge
anage$HighmaxAge[anage$SpeciesLatinName=='Homo sapiens']=anage$maxAge[anage$SpeciesLatinName=='Homo sapiens']
anage$HighmaxAge[anage$SpeciesLatinName=='Mus musculus']=anage$maxAge[anage$SpeciesLatinName=='Mus musculus']
write.csv(anage, "species_annotation.csv")
Writing download.r
[7]:
os.system("Rscript download.r")
[7]:
0
Load features#
From CSV file#
[8]:
df = pd.read_csv('MammalianMethylationConsortium/UniversalPanMammalianClock/ClockParameters/tissue_specific_clock/UniversalSkinClock3_final.csv')
df['feature'] = df['var']
df['coefficient'] = df['beta']
cpg_features = df['feature'][1:].tolist()
anage_df = pd.read_csv('species_annotation.csv', index_col=0)
anage_df = anage_df[~anage_df['averagedMaturity.yrs'].isna()]
anage_df = anage_df[~anage_df['GestationTimeInYears'].isna()]
anage_df = anage_df.reset_index().drop('index', axis=1)
anage_df = anage_df.fillna(0)
species_features = anage_df['SpeciesLatinName'].tolist()
model.features = cpg_features + species_features
Load weights into base model#
[9]:
weights = torch.tensor(df['coefficient'][1:].tolist()).unsqueeze(0)
intercept = torch.tensor([df['coefficient'][0]])
Linear model#
[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]:
reference_list = np.array([0] * len(model.features))
reference_list[len(cpg_features) + np.where(anage_df.SpeciesLatinName == 'Homo sapiens')[0][0]] = 0.5
model.reference_values = reference_list
Load preprocess and postprocess objects#
[12]:
model.preprocess_name = None
model.preprocess_dependencies = None
[13]:
model.postprocess_name = 'mammalian3'
anage_df = anage_df.loc[:, ['GestationTimeInYears','averagedMaturity.yrs', 'maxAge', 'HighmaxAge']]
anage_array = np.array(anage_df)
model.postprocess_dependencies = [anage_array]
Check all clock parameters#
[14]:
pya.utils.print_model_details(model)
%==================================== Model Details ====================================%
Model Attributes:
training: True
metadata: {'approved_by_author': '⌛',
'citation': 'Lu, A. T., et al. "Universal DNA methylation age across '
'mammalian tissues." Nature aging 3.9 (2023): 1144-1166.',
'clock_name': 'mammalianskin3',
'data_type': 'methylation',
'doi': 'https://doi.org/10.1038/s43587-023-00462-6',
'notes': None,
'research_only': None,
'species': 'multi',
'version': None,
'year': 2023}
reference_values: array([0, 0, 0, ..., 0, 0, 0])
preprocess_name: None
preprocess_dependencies: None
postprocess_name: 'mammalian3'
postprocess_dependencies: [array([[2.19178082e-02, 2.49315068e+00, 3.60000000e+01, 4.68000000e+01],
[1.64383562e-02, 3.00000000e+00, 1.15000000e+01, 1.49500000e+01],
[3.01369863e-02, 4.50000000e+00, 1.50000000e+01, 1.95000000e+01],
...,
[1.48575342e-01, 1.15317808e+00, 0.00000000e+00, 0.00000000e+00],
[6.95616438e-02, 1.16958904e-01, 0.00000000e+00, 0.00000000e+00],
[3.15068493e-01, 4.58334000e-01, 2.70000000e+01, 3.51000000e+01]])]
features: ['cg00006213', 'cg00029755', 'cg00046850', 'cg00055211', 'cg00101675', 'cg00109076', 'cg00153046', 'cg00247020', 'cg00281640', 'cg00384342', 'cg00386499', 'cg00438946', 'cg00483633', 'cg00573041', 'cg00623160', 'cg00662491', 'cg00776597', 'cg00823476', 'cg00946032', 'cg01013124', 'cg01019040', 'cg01105418', 'cg01134518', 'cg01161204', 'cg01183821', 'cg01187271', 'cg01296942', 'cg01346827', 'cg01370575', 'cg01429475']... [Total elements: 2055]
base_model_features: None
%==================================== Model Details ====================================%
Model Structure:
base_model: LinearModel(
(linear): Linear(in_features=2055, out_features=1, bias=True)
)
%==================================== Model Details ====================================%
Model Parameters and Weights:
base_model.linear.weight: [0.626102864742279, 0.061784859746694565, -0.2195339798927307, -0.060187797993421555, -0.23942930996418, -0.13619384169578552, -0.8077041506767273, -0.3419697880744934, 0.05137846618890762, -0.012018346227705479, -0.4316115975379944, -0.5612198710441589, 0.2912982404232025, 0.7308650016784668, 0.6431260108947754, 0.08372019231319427, -0.018281029537320137, -0.7829163074493408, -0.31162014603614807, -0.08596483618021011, -0.8132604360580444, -0.13625478744506836, 0.6668254137039185, 0.034686606377363205, 0.7896935343742371, -0.024094825610518456, -0.14803318679332733, -0.010846471413969994, 1.74314546585083, 0.011623219586908817]... [Tensor of shape torch.Size([1, 348])]
base_model.linear.bias: tensor([-0.4431])
%==================================== 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([[ 1.7690e+01],
[ 6.7940e+00],
[ 1.1214e+01],
[ 3.0534e+01],
[ 1.9602e+00],
[-3.5616e-02],
[ 3.4789e+01],
[ 1.3069e+02],
[-6.0273e-02],
[ 3.2328e+00]], 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: species_annotation.csv
Deleted folder: MammalianMethylationConsortium
Deleted file: download.r