Garagnani#

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.Garagnani)
class Garagnani(LinearReferenceClock):
    pass

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

Define clock metadata#

[4]:
model.metadata["clock_name"] = "garagnani"
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"] = 2012
model.metadata["approved_by_author"] = "⌛"
model.metadata["citation"] = "Garagnani, Paolo, et al. \"Methylation of ELOVL2 gene as a new epigenetic marker of age.\" Aging Cell 11.6 (2012): 1132-1134."
model.metadata["doi"] = "https://doi.org/10.1111/acel.12005"
model.metadata["notes"] = "The source study identified age-associated ELOVL2 methylation, but did not publish a one-CpG age equation. Pyaging returns the raw cg16867657 methylation beta value using coefficient 1 and zero intercept; it does not return calibrated chronological age."
model.metadata["research_only"] = None
model.metadata["tissue"] = ["whole blood"]  # Paper: The listed tissue is the model-development sample material.
model.metadata["predicts"] = ["ELOVL2 methylation"]  # Paper: (Intercept),0; cg16867657,1
model.metadata["training_target"] = ["not applicable"]  # Paper: cg16867657 methylation is strongly correlated with chronological age in whole blood.
model.metadata["unit"] = ["beta value"]  # Paper: The packaged single-CpG output is raw cg16867657/ELOVL2 methylation on the beta-value scale.
model.metadata["model_type"] = "single-CpG score"  # Paper: The sole feature has coefficient 1 and the intercept is 0.
model.metadata["platform"] = ["Illumina 450K"]  # Paper: Training/selection used Illumina 450K.
model.metadata["population"] = "all ages"  # Paper: The study includes cord-blood/newborn samples and people through approximately age 99.
model.metadata["journal"] = "Aging Cell"
model.metadata["last_author"] = "Claudio Franceschi"
model.metadata["n_features"] = 1
model.metadata["citations"] = 500
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/Garagnani.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': 'Garagnani, Paolo, et al. "Methylation of ELOVL2 gene as a new '
             'epigenetic marker of age." Aging Cell 11.6 (2012): 1132-1134.',
 'clock_name': 'garagnani',
 'data_type': 'methylation',
 'doi': 'https://doi.org/10.1111/acel.12005',
 'notes': None,
 'research_only': None,
 'species': 'Homo sapiens',
 'version': None,
 'year': 2012}
reference_values: None
preprocess_name: None
preprocess_dependencies: None
postprocess_name: None
postprocess_dependencies: None
features: ['cg16867657']
base_model_features: None

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

base_model: LinearModel(
  (linear): Linear(in_features=1, 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.3367],
        [ 0.1288],
        [ 0.2345],
        [ 0.2303],
        [-1.1229],
        [-0.1863],
        [ 2.2082],
        [-0.6380],
        [ 0.4617],
        [ 0.2674]], 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