StemTOCvitro#

Index#

  1. Instantiate model class

  2. Define clock metadata

  3. Download clock dependencies

  4. Load features

  5. Load weights into base model

  6. Load reference values

  7. Load preprocess and postprocess objects

  8. Check all clock parameters

  9. Basic test

  10. Save torch model

  11. Clear directory

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.StemTOCvitro)
class StemTOCvitro(stemTOC):
    pass

[3]:
model = pya.models.StemTOCvitro()

Define clock metadata#

[4]:
model.metadata["clock_name"] = 'stemtocvitro'
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. \"A pan-tissue DNA methylation atlas enables in silico decomposition of human tissue methylomes at cell-type resolution.\" Nature Communications 15 (2024)."
model.metadata["doi"] = "https://doi.org/10.1038/s41467-024-48649-8"
model.metadata["research_only"] = None
model.metadata["notes"] = "Variant of the StemTOC mitotic counter whose CpGs are defined from cell-division (in vitro) experiments, tracking mitotic age via hypermethylation at sites that accumulate methylation with proliferation rather than merely with chronological time."
model.metadata["tissue"] = 'In vitro proliferating cell lines (fibroblast, endothelial, smooth muscle) used to derive mitCpGs; final CpG selection calibrated against whole-blood age-hypermethylation cohorts; fetal/neonatal…'
model.metadata["predicts"] = 'Mitotic (stem-cell/progenitor division) age'
model.metadata["unit"] = 'score (arbitrary)'
model.metadata["model_type"] = 'Mitotic model'
model.metadata["platform"] = 'Illumina 450K/EPIC'
model.metadata["population"] = 'Pan-age, pan-tissue; applicable to normal, precancerous and cancer tissues (adults, plus fetal/neonatal reference samples used in CpG selection)'
model.metadata["journal"] = 'Nature Communications'
model.metadata["last_author"] = 'Andrew E. Teschendorff'
model.metadata["n_features"] = 629
model.metadata["citations"] = 24
model.metadata["citations_date"] = '2026-07-05'

Download clock dependencies#

[5]:
supplementary_url = "https://raw.githubusercontent.com/Duzhaozhen/OmniAge/c10fbe8cb92957520fbff1d55ae1def0691252e5/OmniAgePy/src/omniage/data/StemTOCvitro.csv"
supplementary_file_name = "coefficients.csv"
os.system(f"curl -sL -o {supplementary_file_name} {supplementary_url}")
[5]:
0

Load features#

[6]:
df = pd.read_csv('coefficients.csv')
if str(df.columns[0]).startswith('Unnamed'):
    df = df.iloc[:, 1:]
model.features = df['probe'].tolist()

Load weights into base model#

[7]:
weights = torch.tensor([1.0]).unsqueeze(0)
intercept = torch.tensor([0.0])
[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. "A pan-tissue DNA methylation atlas enables '
             'in silico decomposition of human tissue methylomes at cell-type '
             'resolution." Nature Communications 15 (2024).',
 'clock_name': 'stemtocvitro',
 'data_type': 'methylation',
 'doi': 'https://doi.org/10.1038/s41467-024-48649-8',
 'notes': None,
 '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: 629]
preprocess_name: '0.95 quantile'
preprocess_dependencies: None
postprocess_name: None
postprocess_dependencies: None
features: ['cg20327258', 'cg23062112', 'cg07365816', 'cg08659394', 'cg14575559', 'cg13294856', 'cg18560328', 'cg21229268', 'cg20078466', 'cg23091824', 'cg03865257', 'cg16443455', 'cg11250773', 'cg10687823', 'cg12892303', 'cg12781700', 'cg13583934', 'cg12065366', 'cg25203031', 'cg17404915', 'cg22299454', 'cg10698404', 'cg09097345', 'cg05404701', 'cg24010885', 'cg17712694', 'cg20707222', 'cg08901752', 'cg11297107', 'cg17876581']... [Total elements: 629]
base_model_features: None

%==================================== Model Details ====================================%
Model Structure:

base_model: LinearModel(
  (linear): Linear(in_features=629, 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.8129],
        [1.7694],
        [1.5825],
        [1.5507],
        [1.6496],
        [1.5994],
        [1.6658],
        [1.6827],
        [1.6054],
        [1.7836]], 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.csv