GrimAge2Leptin#

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:

[34]:
import os
import inspect
import shutil
import json
import torch
import pandas as pd
import pyaging as pya
import numpy as np

Instantiate model class#

[35]:
def print_entire_class(cls):
    source = inspect.getsource(cls)
    print(source)

print_entire_class(pya.models.GrimAge2Leptin)
class GrimAge2Leptin(pyagingModel):
    def __init__(self):
        super().__init__()

    def preprocess(self, x):
        return x

    def postprocess(self, x):
        return x

[36]:
model = pya.models.GrimAge2Leptin()

Define clock metadata#

[37]:
model.metadata["clock_name"] = 'grimage2leptin'
model.metadata["data_type"] = 'methylation'
model.metadata["species"] = 'Homo sapiens'
model.metadata["year"] = 2022
model.metadata["approved_by_author"] = '⌛'
model.metadata["citation"] = "Lu, Ake T., et al. \"DNA methylation GrimAge version 2.\" Aging (Albany NY) 14.23 (2022): 9484."
model.metadata["doi"] = "https://doi.org/10.18632/aging.204434"
model.metadata["research_only"] = True
model.metadata["notes"] = None

Download clock dependencies#

[38]:
logger = pya.logger.Logger()
urls = [
    "https://pyaging.s3.amazonaws.com/supporting_files/grimage2_subcomponents.csv",
    "https://pyaging.s3.amazonaws.com/supporting_files/grimage2.csv",
    "https://pyaging.s3.amazonaws.com/supporting_files/datMiniAnnotation3_Gold.csv",
]
dir = "."
for url in urls:
    pya.utils.download(url, dir, logger, indent_level=1)
|-----------> Downloading data to ./grimage2_subcomponents.csv
|-----------> in progress: 100.0000%
|-----------> Downloading data to ./grimage2.csv
|-----------> in progress: 100.0000%%
|-----------> Downloading data to ./datMiniAnnotation3_Gold.csv
|-----------> in progress: 100.0000%

Load features#

From CSV#

[39]:
df = pd.read_csv('grimage2_subcomponents.csv', index_col=0)
df['Y.pred'].unique()
[39]:
array(['DNAmGDF_15', 'DNAmB2M', 'DNAmCystatin_C', 'DNAmTIMP_1', 'DNAmadm',
       'DNAmpai_1', 'DNAmleptin', 'DNAmPACKYRS', 'DNAmlog.CRP',
       'DNAmlog.A1C'], dtype=object)
[40]:
df = df[df['Y.pred'] == 'DNAmleptin']
df['feature'] = df['var']
df['coefficient'] = df['beta']
model.features = df['feature'][1:].tolist()
[41]:
df.head()
[41]:
Y.pred var beta feature coefficient
1434 DNAmleptin Intercept 7210.062555 Intercept 7210.062555
1435 DNAmleptin cg11781622 399.815717 cg11781622 399.815717
1436 DNAmleptin cg13947317 3861.580695 cg13947317 3861.580695
1437 DNAmleptin cg24145109 4281.873546 cg24145109 4281.873546
1438 DNAmleptin cg19694465 1714.111981 cg19694465 1714.111981

Load weights into base model#

Linear model#

[42]:
weights = torch.tensor(df['coefficient'][1:].tolist()).unsqueeze(0)
intercept = torch.tensor([df['coefficient'].iloc[0]])

Linear model#

[43]:
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#

[44]:
reference_df = pd.read_csv('datMiniAnnotation3_Gold.csv', index_col=0)
model.reference_values = reference_df.loc[model.features[0:]]['gold'].tolist()

Load preprocess and postprocess objects#

[45]:
model.preprocess_name = None
model.preprocess_dependencies = None
[46]:
model.postprocess_name = None
model.postprocess_dependencies = None

Check all clock parameters#

[47]:
pya.utils.print_model_details(model)

%==================================== Model Details ====================================%
Model Attributes:

training: True
metadata: {'approved_by_author': '⌛',
 'citation': 'Lu, Ake T., et al. "DNA methylation GrimAge version 2." Aging '
             '(Albany NY) 14.23 (2022): 9484.',
 'clock_name': 'grimage2leptin',
 'data_type': 'methylation',
 'doi': 'https://doi.org/10.18632/aging.204434',
 'notes': None,
 'research_only': True,
 'species': 'Homo sapiens',
 'version': None,
 'year': 2022}
reference_values: [0.920486032494228, 0.945983138574711, 0.175327347008541, 0.802335112177663, 0.0247552231850483, 0.0173798986148957, 0.0384209480708605, 0.935580510727358, 0.0753967785264462, 0.846802534526148, 0.023407474895155, 0.0258010644664732, 0.580486573508762, 0.134591579250635, 0.248811991314463, 0.0203892784279929, 0.780951039316296, 0.0136097188128507, 0.0428553986489399, 0.930023723262686, 0.9386474887599, 0.0199869326993668, 0.103705423432714, 0.0165397606025236, 0.895587696379722, 0.0420611676843711, 0.838280676738539, 0.0214771540238072, 0.0980339573006406, 0.0239307537419646]... [Total elements: 187]
preprocess_name: None
preprocess_dependencies: None
postprocess_name: 'cox_to_years'
postprocess_dependencies: None
features: ['cg11781622', 'cg13947317', 'cg24145109', 'cg19694465', 'cg15211499', 'cg10511249', 'cg16383389', 'cg04607246', 'cg08926056', 'cg14652203', 'cg20248954', 'cg23814988', 'cg05971102', 'cg07520608', 'cg01412762', 'cg09920725', 'cg12977946', 'cg20150163', 'cg04946715', 'cg08645207', 'cg14716323', 'cg01956624', 'cg00497251', 'cg27114661', 'cg17025841', 'cg06841024', 'cg27326062', 'cg10747042', 'cg18098839', 'cg13457961']... [Total elements: 187]
base_model_features: None

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

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

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

base_model.linear.weight: [399.8157043457031, 3861.580810546875, 4281.87353515625, 1714.1119384765625, -25588.5390625, 25643.771484375, -3710.89697265625, 1028.21484375, 4559.81591796875, -9729.9609375, 28351.38671875, 60980.60546875, 894.3289184570312, 2256.300537109375, -997.83447265625, 16759.64453125, 637.7293090820312, -14579.912109375, -7351.828125, 37.74680709838867, 5151.525390625, -38035.12890625, -3955.989990234375, -2736.428466796875, 154.31683349609375, -5049.8408203125, 4.860612869262695, -59299.390625, -594.4842529296875, 3549.596435546875]... [Tensor of shape torch.Size([1, 187])]
base_model.linear.bias: tensor([7210.0625])

%==================================== Model Details ====================================%

Basic test#

[48]:
torch.manual_seed(42)
input = torch.randn(10, len(model.features), dtype=float).double()
model.eval()
model.to(float)
pred = model(input)
pred
[48]:
tensor([[-120362.4131],
        [-333415.5971],
        [ 129251.7214],
        [  63121.7818],
        [-306690.5105],
        [-118785.7437],
        [  80334.4922],
        [  45302.3369],
        [-291923.9350],
        [ 357345.7592]], dtype=torch.float64, grad_fn=<AddmmBackward0>)

Save torch model#

[49]:
torch.save(model, f"../weights/{model.metadata['clock_name']}.pt")

Clear directory#

[50]:
# 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: grimage2_subcomponents.csv
Deleted file: datMiniAnnotation3_Gold.csv
Deleted file: grimage2.csv