Mayne#
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.Mayne)
class Mayne(LinearReferenceClock):
def postprocess(self, x):
"""Gestational age in weeks (as published)."""
return x
[3]:
model = pya.models.Mayne()
Define clock metadata#
[4]:
model.metadata["clock_name"] = "mayne"
model.metadata["data_type"] = "DNA methylation" # Paper: The model is based on DNA methylation measurements.
model.metadata["species"] = "Homo sapiens" # Paper: The study samples are Homo sapiens.
model.metadata["year"] = 2017
model.metadata["approved_by_author"] = "⌛"
model.metadata["citation"] = "Mayne, Benjamin T., et al. \"Accelerated placental aging in early onset preeclampsia pregnancies identified by DNA methylation.\" Epigenomics 9 (2017): 279–289."
model.metadata["doi"] = "https://doi.org/10.2217/epi-2016-0103"
model.metadata["notes"] = "Placental elastic-net clock trained on pooled healthy human placenta methylation datasets; 62 selected CpGs predict gestational age and were used to test age acceleration in early-onset preeclampsia."
model.metadata["research_only"] = None
model.metadata["tissue"] = ["placenta"] # Paper: The listed tissue is the model-development sample material.
model.metadata["predicts"] = ["gestational age"] # Paper: The reported predictor output is gestational age.
model.metadata["training_target"] = ["gestational age"] # Paper: The fitting outcome is gestational age.
model.metadata["unit"] = ["weeks"] # Paper: The returned construct is expressed as weeks.
model.metadata["model_type"] = "elastic net regression" # Paper: The clock was fitted using Elastic net.
model.metadata["platform"] = ["Illumina 27K", "Illumina 450K"] # Paper: Training/selection used Illumina 27K/450K.
model.metadata["population"] = "pregnancies" # Paper: healthy human placentas sampled across gestation
model.metadata["journal"] = "Epigenomics"
model.metadata["last_author"] = "Tina Bianco‐Miotto"
model.metadata["n_features"] = 62
model.metadata["citations"] = 150
model.metadata["citations_date"] = "2026-07-05"
Download clock dependencies#
[5]:
os.system(f"curl -sL -o coefficients.csv https://raw.githubusercontent.com/Duzhaozhen/OmniAge/c10fbe8cb92957520fbff1d55ae1def0691252e5/OmniAgePy/src/omniage/data/Mayne_GA.csv")
[5]:
0
Load features#
[6]:
df = pd.read_csv('coefficients.csv')
mask = df['probe'].astype(str).str.lower().isin(['intercept', '(intercept)'])
intercept_value = float(df.loc[mask, 'coef'].iloc[0]) if mask.any() else 0.0
coef_df = df.loc[~mask].reset_index(drop=True)
model.features = coef_df['probe'].tolist()
Load weights into base model#
[7]:
weights = torch.tensor(coef_df['coef'].tolist()).unsqueeze(0).float()
intercept = torch.tensor([intercept_value]).float()
[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 = None
Load preprocess and postprocess objects#
[10]:
model.preprocess_name = None
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': 'Mayne, Benjamin T., et al. "Accelerated placental aging in early '
'onset preeclampsia pregnancies identified by DNA methylation." '
'Epigenomics 9.3 (2017): 279-289.',
'clock_name': 'mayne',
'data_type': 'methylation',
'doi': 'https://doi.org/10.2217/epi-2016-0103',
'notes': None,
'research_only': None,
'species': 'Homo sapiens',
'version': None,
'year': 2017}
reference_values: None
preprocess_name: None
preprocess_dependencies: None
postprocess_name: None
postprocess_dependencies: None
features: ['cg12146151', 'cg16127845', 'cg17133388', 'cg13997435', 'cg12360736', 'cg07300408', 'cg11739626', 'cg00828602', 'cg21624359', 'cg22639768', 'cg11388238', 'cg06958211', 'cg19317715', 'cg20291222', 'cg03490200', 'cg26353877', 'cg22957381', 'cg19742789', 'cg02976574', 'cg16356956', 'cg26143719', 'cg09990086', 'cg16746631', 'cg10245048', 'cg00047050', 'cg25623459', 'cg25374854', 'cg02589695', 'cg19289461', 'cg16816226']... [Total elements: 62]
base_model_features: None
%==================================== Model Details ====================================%
Model Structure:
base_model: LinearModel(
(linear): Linear(in_features=62, out_features=1, bias=True)
)
%==================================== Model Details ====================================%
Model Parameters and Weights:
base_model.linear.weight: [-1.9282536506652832, -26.4451904296875, -17.35150718688965, -0.9527280330657959, -5.665579319000244, -2.0989339351654053, -0.7110825181007385, -0.03753948584198952, -2.35093355178833, -2.3877365589141846, -4.450428009033203, -0.32594966888427734, -2.3679003715515137, -3.580242156982422, -4.025350570678711, -0.034084122627973557, -5.023456573486328, -10.068197250366211, -6.389592170715332, -0.3280542492866516, -0.40900924801826477, -5.404386043548584, -6.043520927429199, -0.026322754099965096, -1.531197428703308, -2.4376535415649414, -0.4204040467739105, -7.178297996520996, -3.049933433532715, -1.4748220443725586]... [Tensor of shape torch.Size([1, 62])]
base_model.linear.bias: tensor([24.9903])
%==================================== 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([[ -39.5419],
[ 25.7659],
[ 44.2797],
[ -0.9077],
[ 92.4899],
[ 86.2686],
[-106.0699],
[ 76.7959],
[ 20.1038],
[ 21.3373]], 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