EpiCMITHyper#

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

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

Define clock metadata#

[4]:
model.metadata["clock_name"] = "epicmithyper"
model.metadata["data_type"] = "DNA methylation"  # Paper: methylation
model.metadata["species"] = "Homo sapiens"  # Paper: Homo sapiens
model.metadata["year"] = 2020
model.metadata["approved_by_author"] = "⌛"
model.metadata["citation"] = "Duran-Ferrer, M., et al. \"The proliferative history shapes the DNA methylome of B-cell tumors and predicts clinical outcome.\" Nature Cancer 1 (2020): 1066-1081."
model.metadata["doi"] = "https://doi.org/10.1038/s43018-020-00131-2"
model.metadata["notes"] = "Hypermethylation component of epiCMIT: a 184-CpG score ranging from 0 to 1 that tracks low-to-high relative proliferative history in normal and neoplastic B cells."
model.metadata["research_only"] = None
model.metadata["tissue"] = ["B cells"]  # Paper: normal and neoplastic B cells
model.metadata["predicts"] = ["mitotic age"]  # Paper: The author tutorial states both component clocks range from 0 to 1 and report relative proliferative history.
model.metadata["training_target"] = ["replicative history"]  # Paper: relative proliferative history
model.metadata["unit"] = ["proportion"]  # Paper: The author tutorial states both component clocks range from 0 to 1 and report relative proliferative history.
model.metadata["model_type"] = "mean methylation aggregation"  # Paper: Mean methylation score
model.metadata["platform"] = ["Illumina 450K", "Illumina EPIC"]  # Paper: Illumina 450K; Illumina EPIC
model.metadata["population"] = "human, age unspecified"  # Paper: 1,595 human samples spanning normal B-cell subpopulations and 14 B-cell tumor subtypes
model.metadata["journal"] = "Nature Cancer"
model.metadata["last_author"] = "José I. Martín-Subero"
model.metadata["n_features"] = 184
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('hyper', case=False)]
model.features = df['Name'].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 = "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': 'epicmithyper',
 '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: 184]
preprocess_name: 'mean'
preprocess_dependencies: None
postprocess_name: None
postprocess_dependencies: None
features: ['cg19715410', 'cg18279094', 'cg11823511', 'cg24453699', 'cg03989260', 'cg14565725', 'cg00466334', 'cg24035245', 'cg05378938', 'cg09671258', 'cg09826050', 'cg07279070', 'cg18093372', 'cg18173235', 'cg07813142', 'cg24772753', 'cg17737681', 'cg17078253', 'cg05467160', 'cg04415176', 'cg01405040', 'cg02694427', 'cg03964958', 'cg09578028', 'cg04739647', 'cg05167251', 'cg22674699', 'cg22541735', 'cg19384289', 'cg14473102']... [Total elements: 184]
base_model_features: None

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

base_model: LinearModel(
  (linear): Linear(in_features=184, 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.0423],
        [ 0.0471],
        [ 0.0455],
        [ 0.0341],
        [ 0.0093],
        [ 0.0674],
        [ 0.0421],
        [ 0.0545],
        [ 0.0112],
        [-0.1275]], 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