Wu#

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.Wu)
class Wu(LinearReferenceClock):
    def postprocess(self, x):
        """Horvath anti-log (adult age = 48) giving months, then months to years."""
        adult_age = 48
        mask_negative = x < 0
        mask_non_negative = ~mask_negative
        age = torch.empty_like(x)
        age[mask_negative] = (1 + adult_age) * torch.exp(x[mask_negative]) - 1
        age[mask_non_negative] = (1 + adult_age) * x[mask_non_negative] + adult_age
        return age / 12.0

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

Define clock metadata#

[4]:
model.metadata["clock_name"] = "wu"
model.metadata["data_type"] = "DNA methylation"  # Paper: The model predicts child age from blood DNA methylation.
model.metadata["species"] = "Homo sapiens"  # Paper: The model was built from healthy children's blood samples.
model.metadata["year"] = 2019
model.metadata["approved_by_author"] = "⌛"
model.metadata["citation"] = "Wu, X., et al. “DNA methylation profile is a quantitative measure of biological aging in children.” Aging 11(22): 10031–10051 (2019)."
model.metadata["doi"] = "https://doi.org/10.18632/aging.102399"
model.metadata["notes"] = "Child-specific 111-CpG blood age predictor built by sure independence screening followed by elastic net; pyaging converts the published month-scale output to years."
model.metadata["research_only"] = None
model.metadata["tissue"] = ["whole blood"]  # Paper: Healthy children's peripheral blood datasets were used to build the model.
model.metadata["predicts"] = ["chronological age"]  # Paper: The model's DNA methylation age closely predicted chronological age.
model.metadata["training_target"] = ["chronological age"]  # Paper: Age was converted to months and transformed by function F before elastic-net fitting.
model.metadata["unit"] = ["years"]  # Paper: The packaged postprocess applies the published inverse age transform in months and divides by 12.
model.metadata["model_type"] = "screened elastic net regression"  # Paper: Sure independence screening reduced dimensionality before glmnet elastic-net regression.
model.metadata["platform"] = ["Illumina 27K", "Illumina 450K"]  # Paper: Five training datasets used 27K and six used 450K; fitting used shared probes.
model.metadata["population"] = "children"  # Paper: The model used 716 child blood samples aged 9–212 months.
model.metadata["journal"] = "Aging"
model.metadata["last_author"] = "Huiying Liang"
model.metadata["n_features"] = 111
model.metadata["citations"] = 82
model.metadata["citations_date"] = "2026-07-05"

Download clock dependencies#

[5]:
os.system(f"curl -sL -o wu.xlsx https://cdn.aging-us.com/article/102399/supplementary/SD3/0/aging-v11i22-102399-supplementary-material-SD3.xlsx")
[5]:
0

Load features#

[6]:
df = pd.read_excel('wu.xlsx', sheet_name='CpGs_information')
mask = df['CpGs'].astype(str).str.lower().isin(['intercept', '(intercept)'])
intercept_value = float(df.loc[mask, 'Active.coefficients'].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['Active.coefficients'].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 = 'anti_log_linear'
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': 'Wu, Xiaohui, et al. "DNA methylation profile is a quantitative '
             'measure of biological aging in children." Aging 11.22 (2019): '
             '10031-10051.',
 'clock_name': 'wu',
 'data_type': 'methylation',
 'doi': 'https://doi.org/10.18632/aging.102399',
 'notes': None,
 'research_only': None,
 'species': 'Homo sapiens',
 'version': None,
 'year': 2019}
reference_values: None
preprocess_name: None
preprocess_dependencies: None
postprocess_name: 'anti_log_linear'
postprocess_dependencies: None
features: ['cg00343092', 'cg00563932', 'cg00571634', 'cg00629217', 'cg01511567', 'cg01515426', 'cg01756060', 'cg01899253', 'cg02385474', 'cg02489552', 'cg02626929', 'cg02789485', 'cg03224418', 'cg03340261', 'cg03970609', 'cg04458548', 'cg04460372', 'cg04474832', 'cg04527989', 'cg04784672', 'cg05073035', 'cg05228408', 'cg05294455', 'cg05352668', 'cg05921699', 'cg05995267', 'cg06204948', 'cg06495803', 'cg07408456', 'cg08032971']... [Total elements: 111]
base_model_features: None

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

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

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

base_model.linear.weight: [-1.1359976530075073, -2.2549679279327393, 1.2051302194595337, -1.4431147575378418, 0.5572546720504761, -4.753889083862305, -2.9755256175994873, -0.8770837783813477, -1.1014573574066162, 0.5342934727668762, 0.128916397690773, 0.35315999388694763, -0.16534864902496338, -6.689713954925537, 0.563336193561554, -0.28343427181243896, -0.9679408669471741, -1.2036683559417725, 0.6776095032691956, 1.7862359285354614, 1.216035008430481, -0.6090858578681946, 0.9103692173957825, -1.5713691711425781, 1.8002407550811768, 0.6004332900047302, 0.6391267776489258, 0.3963273763656616, -2.025444269180298, 0.6885870695114136]... [Tensor of shape torch.Size([1, 111])]
base_model.linear.bias: tensor([2.3769])

%==================================== 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([[ 7.1793e+01],
        [ 3.4194e+00],
        [-8.3333e-02],
        [ 2.7208e-01],
        [-8.3328e-02],
        [ 4.4315e+01],
        [ 1.1845e+02],
        [-8.2270e-02],
        [-8.3325e-02],
        [ 2.5722e+01]], 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: wu.xlsx