EpiCMITHypo#

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.EpiCMITHypo)
class EpiCMITHypo(epiTOC1):
    pass

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

Define clock metadata#

[4]:
model.metadata["clock_name"] = 'epicmithypo'
model.metadata["data_type"] = 'methylation'
model.metadata["species"] = 'Homo sapiens'
model.metadata["year"] = 2020
model.metadata["approved_by_author"] = '⌛'
model.metadata["citation"] = "Duran-Ferrer, Marti, et al. \"The proliferative history shapes the DNA methylome of B-cell tumors and predicts clinical outcome.\" Nature Cancer 1.11 (2020): 1066-1081."
model.metadata["doi"] = "https://doi.org/10.1038/s43018-020-00131-2"
model.metadata["research_only"] = None
model.metadata["notes"] = "Hypomethylation-based component of the epiCMIT mitotic clock, tracking the cumulative mitotic history of B cells from progressive loss of DNA methylation in heterochromatin and serving as an independent prognostic marker in B-cell malignancies."
model.metadata["tissue"] = 'B cells / B-cell tumors (normal B-cell subpopulations and neoplasms: ALL, MCL, DLBCL, CLL, MM)'
model.metadata["predicts"] = 'mitotic age / cumulative proliferative history (hypomethylation component)'
model.metadata["unit"] = 'score (arbitrary)'
model.metadata["model_type"] = 'Mitotic model'
model.metadata["platform"] = 'Illumina 450K/EPIC'
model.metadata["population"] = 'B-cell tumor patients and normal B cells (human)'
model.metadata["journal"] = 'Nature Cancer'
model.metadata["last_author"] = 'José I. Martı́n-Subero'
model.metadata["n_features"] = 1164
model.metadata["citations"] = 104
model.metadata["citations_date"] = '2026-07-05'

Download clock dependencies#

[5]:
supplementary_url = "https://static-content.springer.com/esm/art%3A10.1038%2Fs43018-020-00131-2/MediaObjects/43018_2020_131_MOESM3_ESM.xlsx"
supplementary_file_name = "epicmit.xlsx"
os.system(f"curl -sL -o {supplementary_file_name} {supplementary_url}")
[5]:
0

Load features#

[6]:
df = pd.read_excel('epicmit.xlsx', sheet_name='Table 23')
df = df[df['epiCMIT.class'].astype(str).str.contains('hypo', case=False)]
model.features = df['Name'].tolist()

Load weights into base model#

[7]:
weights = torch.tensor([-1.0]).unsqueeze(0)
intercept = torch.tensor([1.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 = "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': 'Duran-Ferrer, Marti, et al. "The proliferative history shapes '
             'the DNA methylome of B-cell tumors and predicts clinical '
             'outcome." Nature Cancer 1.11 (2020): 1066-1081.',
 'clock_name': 'epicmithypo',
 'data_type': 'methylation',
 'doi': 'https://doi.org/10.1038/s43018-020-00131-2',
 'notes': None,
 'research_only': None,
 'species': 'Homo sapiens',
 'version': None,
 'year': 2020}
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: 1164]
preprocess_name: 'mean'
preprocess_dependencies: None
postprocess_name: None
postprocess_dependencies: None
features: ['cg21870274', 'cg17810211', 'cg08263140', 'cg05663262', 'cg00055603', 'cg05042706', 'cg25469314', 'cg16515477', 'cg07910726', 'cg22037030', 'cg00954256', 'cg13047196', 'cg04910179', 'cg08123701', 'cg14777634', 'cg11795488', 'cg21679730', 'cg11228758', 'cg13784017', 'cg17987458', 'cg12302119', 'cg05928873', 'cg17041296', 'cg16926302', 'cg11338128', 'cg05948962', 'cg01952027', 'cg17175521', 'cg17011453', 'cg26032419']... [Total elements: 1164]
base_model_features: None

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

base_model: LinearModel(
  (linear): Linear(in_features=1164, out_features=1, bias=True)
)

%==================================== Model Details ====================================%
Model Parameters and Weights:

base_model.linear.weight: tensor([[-1.]])
base_model.linear.bias: tensor([1.])

%==================================== 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.9526],
        [1.0553],
        [1.0356],
        [0.9706],
        [1.0003],
        [0.9377],
        [1.0229],
        [1.0117],
        [1.0650],
        [0.9722]], 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: epicmit.xlsx