EPICGA#
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.EPICGA)
class EPICGA(LinearReferenceClock):
def postprocess(self, x):
"""Model returns gestational age in days; convert to weeks."""
return x / 7.0
[3]:
model = pya.models.EPICGA()
Define clock metadata#
[4]:
model.metadata["clock_name"] = "epicga"
model.metadata["data_type"] = "DNA methylation" # Paper: An EPIC DNA-methylation predictor of gestational age.
model.metadata["species"] = "Homo sapiens" # Paper: An EPIC DNA-methylation predictor of gestational age.
model.metadata["year"] = 2021
model.metadata["approved_by_author"] = "⌛"
model.metadata["citation"] = "Haftorn, K. L. et al. An EPIC predictor of gestational age and its application to newborns conceived by assisted reproductive technologies. Clinical Epigenetics 13, 82 (2021)."
model.metadata["doi"] = "https://doi.org/10.1186/s13148-021-01055-z"
model.metadata["notes"] = "LASSO predictor of ultrasound-estimated gestational age in days from umbilical cord-blood DNA methylation, trained in 755 non-ART START newborns."
model.metadata["research_only"] = None
model.metadata["tissue"] = ["cord blood"] # Paper: Cord blood samples were taken immediately after birth.
model.metadata["predicts"] = ["gestational age"] # Paper: An EPIC DNA-methylation predictor of gestational age.
model.metadata["training_target"] = ["gestational age"] # Paper: Clinically estimated gestational age was regressed on CpGs.
model.metadata["unit"] = ["days"] # Paper: Intercept 293.4557 and coefficients reproduce gestational age in days.
model.metadata["model_type"] = "LASSO regression" # Paper: Lasso regression selected 176 CpGs.
model.metadata["platform"] = ["Illumina EPIC"] # Paper: An EPIC DNA-methylation predictor of gestational age.
model.metadata["population"] = "newborns" # Paper: The clock was trained on 755 non-ART newborns from START.
model.metadata["journal"] = "Clinical Epigenetics"
model.metadata["last_author"] = "Jon Bohlin"
model.metadata["n_features"] = 176
model.metadata["citations"] = 54
model.metadata["citations_date"] = "2026-07-05"
Download clock dependencies#
[5]:
supplementary_url = "https://static-content.springer.com/esm/art%3A10.1186%2Fs13148-021-01055-z/MediaObjects/13148_2021_1055_MOESM7_ESM.csv"
supplementary_file_name = "epic_ga_coefs.csv"
os.system(f"curl -sL -o {supplementary_file_name} {supplementary_url}")
[5]:
0
Load features#
[6]:
df = pd.read_csv('epic_ga_coefs.csv')
mask = df['cpgs'].astype(str).str.lower().isin(['intercept', '(intercept)'])
intercept_value = float(df.loc[mask, 's0'].iloc[0]) if mask.any() else 0.0
coef_df = df.loc[~mask].reset_index(drop=True)
model.features = coef_df['cpgs'].tolist()
Load weights into base model#
[7]:
weights = torch.tensor(coef_df['s0'].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 = 'days_to_weeks'
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': 'Haftorn, Kristine L., et al. "An EPIC predictor of gestational '
'age and its application to newborns conceived by assisted '
'reproductive technologies." Clinical Epigenetics 13.1 (2021): '
'82.',
'clock_name': 'epicga',
'data_type': 'methylation',
'doi': 'https://doi.org/10.1186/s13148-021-01055-z',
'notes': None,
'research_only': None,
'species': 'Homo sapiens',
'version': None,
'year': 2021}
reference_values: None
preprocess_name: None
preprocess_dependencies: None
postprocess_name: 'days_to_weeks'
postprocess_dependencies: None
features: ['cg12701018', 'cg00078456', 'cg14958032', 'cg00735586', 'cg09035049', 'cg23915699', 'cg24741609', 'cg00996847', 'cg12079303', 'cg20301308', 'cg21141647', 'cg13189264', 'cg16246545', 'cg06902698', 'cg01281797', 'cg01833485', 'cg12434132', 'cg06046912', 'cg11147204', 'cg19672145', 'cg02968445', 'cg09116068', 'cg07749613', 'cg21155834', 'cg15433843', 'cg12685296', 'cg22871331', 'cg25241559', 'cg06900004', 'cg20582941']... [Total elements: 176]
base_model_features: None
%==================================== Model Details ====================================%
Model Structure:
base_model: LinearModel(
(linear): Linear(in_features=176, out_features=1, bias=True)
)
%==================================== Model Details ====================================%
Model Parameters and Weights:
base_model.linear.weight: [-0.09159819036722183, -2.3058528900146484, -0.4794044494628906, -11.715208053588867, -8.509488105773926, -0.5367807149887085, -0.32814541459083557, 1.0927908420562744, 1.626057744026184, -10.894654273986816, 1.7147382497787476, -8.59422492980957, 0.3499724566936493, 2.7312521934509277, 3.7085211277008057, 6.265093803405762, -3.1235597133636475, -0.5551669597625732, -4.767549991607666, 25.61239242553711, 1.6901012659072876, 1.5959044694900513, -32.38628387451172, -2.249823808670044, 11.97744369506836, 6.300745010375977, -0.7150956988334656, -0.45685043931007385, 3.390894889831543, -7.354003429412842]... [Tensor of shape torch.Size([1, 176])]
base_model.linear.bias: tensor([293.4557])
%==================================== 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([[60.5326],
[42.4761],
[51.9958],
[58.1296],
[27.9050],
[42.0799],
[33.6746],
[32.6965],
[63.3254],
[42.7455]], dtype=torch.float64, grad_fn=<DivBackward0>)
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: epic_ga_coefs.csv