stemTOC#

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.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"] = "DNA methylation"  # Paper: The study constructs clocks from DNA methylation measurements.
model.metadata["species"] = "Homo sapiens"  # Paper: The analyzed samples and clock are human.
model.metadata["year"] = 2024
model.metadata["approved_by_author"] = "✅"
model.metadata["citation"] = "Zhu, Tianlei, et al. \"An improved epigenetic counter to track mitotic age in cells.\" Nature Communications 15 (2024): 4211."
model.metadata["doi"] = "https://doi.org/10.1038/s41467-024-48649-8"
model.metadata["notes"] = "Relative mitotic-age counter based on the 95th percentile across 371 in-vivo-filtered mitotic CpGs."
model.metadata["research_only"] = None
model.metadata["tissue"] = ["multi-tissue", "cultured human cells", "whole blood"]  # Paper: Feature selection used fetal/neonatal reference tissues and cultured normal cell types; stemTOC also used blood cohorts.
model.metadata["predicts"] = ["mitotic age"]  # Paper: The paper describes the returned score as relative mitotic age.
model.metadata["training_target"] = ["population doublings", "chronological age"]  # Paper: Candidate CpGs were selected for methylation gain with population doublings and, where applicable, age in blood.
model.metadata["unit"] = ["beta value"]  # Paper: The score is the 95% upper quantile of CpG DNAm beta values.
model.metadata["model_type"] = "95th-percentile methylation aggregation"  # Paper: The score is computed as the 95% upper quantile across selected CpGs.
model.metadata["platform"] = ["Illumina 450K", "Illumina EPIC"]  # Paper: Derivation datasets included 450K fetal samples and EPIC cultured-cell samples.
model.metadata["population"] = "all ages"  # Paper: The derivation cohorts are fetal/neonatal tissues, normal cell cultures, and for stemTOC adult blood cohorts.
model.metadata["journal"] = "Nature Communications"
model.metadata["last_author"] = "Andrew E. Teschendorff"
model.metadata["n_features"] = 371
model.metadata["citations"] = 24
model.metadata["citations_date"] = "2026-07-05"

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