stemTOC#
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.stemTOC)
class stemTOC(pyagingModel):
def __init__(self):
super().__init__()
def preprocess(self, x):
# Filter out -1 values per row and calculate the 0.95 quantile per row
quantiles = []
for row in x:
filtered_row = row[row != -1]
if len(filtered_row) > 0:
quantile_95 = torch.quantile(filtered_row, 0.95)
else:
quantile_95 = torch.tensor(float('nan'))
quantiles.append(quantile_95)
return torch.vstack(quantiles)
def postprocess(self, x):
return x
[3]:
model = pya.models.stemTOC()
Define clock metadata#
[4]:
model.metadata["clock_name"] = 'stemtoc'
model.metadata["data_type"] = 'methylation'
model.metadata["species"] = 'Homo sapiens'
model.metadata["year"] = 2024
model.metadata["approved_by_author"] = '✅'
model.metadata["citation"] = "Zhu, Tianyu, et al. \"An improved epigenetic counter to track mitotic age in normal and precancerous tissues.\" Nature Communications 15.1 (2024): 4211."
model.metadata["doi"] = "https://doi.org/10.1038/s41467-024-48649-8"
model.metadata["research_only"] = None
model.metadata["notes"] = "The reference values are simply -1 for the algorithm to ignore them."
Download clock dependencies#
Download directly with curl#
[5]:
supplementary_url = "https://static-content.springer.com/esm/art%3A10.1038%2Fs41467-024-48649-8/MediaObjects/41467_2024_48649_MOESM4_ESM.xlsx"
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='SuppData1', skiprows=1)
df['feature'] = df['ProbeID'].astype(str)
model.features = df['feature'].tolist()
Load weights into base model#
[7]:
weights = torch.tensor([1.0]).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 = [-1]*len(model.features)
Load preprocess and postprocess objects#
[10]:
model.preprocess_name = "0.95 quantile"
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': 'Zhu, Tianyu, et al. "An improved epigenetic counter to track '
'mitotic age in normal and precancerous tissues." Nature '
'Communications 15.1 (2024): 4211.',
'clock_name': 'stemtoc',
'data_type': 'methylation',
'doi': 'https://doi.org/10.1038/s41467-024-48649-8',
'notes': 'The reference values are simply -1 for the algorithm to ignore '
'them.',
'research_only': None,
'species': 'Homo sapiens',
'version': None,
'year': 2024}
reference_values: [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1]... [Total elements: 371]
preprocess_name: '0.95 quantile'
preprocess_dependencies: None
postprocess_name: None
postprocess_dependencies: None
features: ['cg23062112', 'cg07365816', 'cg08659394', 'cg14575559', 'cg18560328', 'cg21229268', 'cg23091824', 'cg03865257', 'cg11250773', 'cg12892303', 'cg12781700', 'cg13583934', 'cg12065366', 'cg25203031', 'cg17404915', 'cg22299454', 'cg05404701', 'cg24010885', 'cg17712694', 'cg20707222', 'cg11297107', 'cg12799781', 'cg01718742', 'cg10263370', 'cg15774465', 'cg16491617', 'cg11832210', 'cg07686635', 'cg26510017', 'cg15745900']... [Total elements: 371]
base_model_features: None
%==================================== Model Details ====================================%
Model Structure:
base_model: LinearModel(
(linear): Linear(in_features=371, out_features=1, bias=True)
)
%==================================== Model Details ====================================%
Model Parameters and Weights:
base_model.linear.weight: tensor([[1.]])
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([[1.7652],
[1.7920],
[1.8101],
[1.6322],
[1.7383],
[1.4275],
[1.6186],
[1.8202],
[1.5886],
[1.6065]], 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: coefficients.xlsx