epiTOC1#
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.epiTOC1)
class epiTOC1(pyagingModel):
def __init__(self):
super().__init__()
def preprocess(self, x):
# Filter out -1 values per row and calculate the mean per row
means = []
for row in x:
filtered_row = row[row != -1]
if len(filtered_row) > 0:
mean = torch.mean(filtered_row)
else:
mean = torch.tensor(float('nan'))
means.append(mean)
return torch.vstack(means)
def postprocess(self, x):
return x
[3]:
model = pya.models.epiTOC1()
Define clock metadata#
[4]:
model.metadata["clock_name"] = 'epitoc1'
model.metadata["data_type"] = 'methylation'
model.metadata["species"] = 'Homo sapiens'
model.metadata["year"] = 2016
model.metadata["approved_by_author"] = '✅'
model.metadata["citation"] = "Yang, Zhen, et al. \"Correlation of an epigenetic mitotic clock with cancer risk.\" Genome biology 17 (2016): 1-18."
model.metadata["doi"] = "https://doi.org/10.1186/s13059-016-1064-3"
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.1186%2Fs13059-016-1064-3/MediaObjects/13059_2016_1064_MOESM2_ESM.xls"
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='agehyperPCGT-tableS1', skiprows=1)
df['feature'] = df['CpG'].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 = "mean"
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': 'Yang, Zhen, et al. "Correlation of an epigenetic mitotic clock '
'with cancer risk." Genome biology 17 (2016): 1-18.',
'clock_name': 'epitoc1',
'data_type': 'methylation',
'doi': 'https://doi.org/10.1186/s13059-016-1064-3',
'notes': 'The reference values are simply -1 for the algorithm to ignore '
'them.',
'research_only': None,
'species': 'Homo sapiens',
'version': None,
'year': 2016}
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: 385]
preprocess_name: 'mean'
preprocess_dependencies: None
postprocess_name: None
postprocess_dependencies: None
features: ['cg00043095', 'cg00060320', 'cg00181968', 'cg00329270', 'cg00347369', 'cg00397986', 'cg00466268', 'cg00665492', 'cg00884606', 'cg00916884', 'cg00930628', 'cg00962913', 'cg01050423', 'cg01185626', 'cg01435574', 'cg01537995', 'cg01587896', 'cg01670677', 'cg01699217', 'cg01783070', 'cg01830294', 'cg02004418', 'cg02056682', 'cg02071825', 'cg02150988', 'cg02160530', 'cg02186542', 'cg02266732', 'cg02315940', 'cg02554246']... [Total elements: 385]
base_model_features: None
%==================================== Model Details ====================================%
Model Structure:
base_model: LinearModel(
(linear): Linear(in_features=385, 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([[ 0.0669],
[-0.0019],
[ 0.0772],
[ 0.0336],
[-0.1134],
[-0.0825],
[-0.0375],
[-0.0160],
[-0.0543],
[-0.0141]], 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
Deleted folder: .ipynb_checkpoints