CompIL6#

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

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

Define clock metadata#

[4]:
model.metadata["clock_name"] = "compil6"
model.metadata["data_type"] = "DNA methylation"  # Paper: A DNA-methylation predictor of IL-6 was developed from CpG methylation levels.
model.metadata["species"] = "Homo sapiens"  # Paper: The training cohort comprised Lothian Birth Cohort 1936 participants.
model.metadata["year"] = 2021
model.metadata["approved_by_author"] = "⌛"
model.metadata["citation"] = "Stevenson, A. J., et al. “Creating and Validating a DNA Methylation-Based Proxy for Interleukin-6.” The Journals of Gerontology: Series A 76(12): 2284–2292 (2021)."
model.metadata["doi"] = "https://doi.org/10.1093/gerona/glab046"
model.metadata["notes"] = "Thirty-five-CpG whole-blood proxy score for persistent IL-6-related inflammatory burden, fitted against covariate-adjusted normalized plasma IL-6."
model.metadata["research_only"] = None
model.metadata["tissue"] = ["whole blood"]  # Paper: DNA extracted from whole blood supplied the methylation predictors.
model.metadata["predicts"] = ["interleukin-6"]  # Paper: The 35-CpG weighted sum was generated as a DNAm proxy for IL-6.
model.metadata["training_target"] = ["interleukin-6"]  # Paper: IL-6 NPX was inverse normalized and adjusted for age, sex, genetic principal components, and Olink plate; standardized residuals entered penalized regression.
model.metadata["unit"] = ["unitless"]  # Paper: The proxy is computed by multiplying beta values by coefficients and summing into one score.
model.metadata["model_type"] = "elastic net regression"  # Paper: The elastic net model used glmnet with 12-fold cross-validation and alpha 0.5.
model.metadata["platform"] = ["Illumina 450K"]  # Paper: Training whole-blood DNA was analyzed on the Illumina 450K BeadChip.
model.metadata["population"] = "older adults"  # Paper: The predictor was developed in 875 LBC1936 older adults with mean age 70.
model.metadata["journal"] = "The Journals of Gerontology: Series A"
model.metadata["last_author"] = "Riccardo E. Marioni"
model.metadata["n_features"] = 35
model.metadata["citations"] = 55
model.metadata["citations_date"] = "2026-07-05"

Download clock dependencies#

[5]:
supplementary_url = "https://raw.githubusercontent.com/Duzhaozhen/OmniAge/c10fbe8cb92957520fbff1d55ae1def0691252e5/OmniAgePy/src/omniage/data/CompIL6.csv"
supplementary_file_name = "coefficients.csv"
os.system(f"curl -sL -o {supplementary_file_name} {supplementary_url}")
[5]:
0

Load features#

[6]:
df = pd.read_csv('coefficients.csv')
if str(df.columns[0]).startswith('Unnamed'):
    df = df.iloc[:, 1:]
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': 'Stevenson, Anna J., et al. "Creating and validating a DNA '
             'methylation-based proxy for interleukin-6." The Journals of '
             'Gerontology: Series A 76.12 (2021): 2284-2292.',
 'clock_name': 'compil6',
 'data_type': 'methylation',
 'doi': 'https://doi.org/10.1093/gerona/glab046',
 'notes': None,
 'research_only': None,
 'species': 'Homo sapiens',
 'version': None,
 'year': 2021}
reference_values: None
preprocess_name: None
preprocess_dependencies: None
postprocess_name: None
postprocess_dependencies: None
features: ['cg26144437', 'cg03076319', 'cg05575921', 'cg21368161', 'cg04642923', 'cg21123519', 'cg04583842', 'cg16357224', 'cg24455236', 'cg25323809', 'cg03885055', 'cg17412005', 'cg19638572', 'cg04921989', 'cg14965639', 'cg04381957', 'cg20789595', 'cg24935598', 'cg26230601', 'cg16508480', 'cg12503394', 'cg18925601', 'cg19584649', 'cg03245734', 'cg04366687', 'cg14044707', 'cg25250132', 'cg04468741', 'cg23729763', 'cg10195814']... [Total elements: 35]
base_model_features: None

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

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

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

base_model.linear.weight: [0.05400000140070915, 0.3799999952316284, -0.14000000059604645, 0.11999999731779099, 0.25, 0.004999999888241291, 0.00019999999494757503, 0.003599999938160181, 0.06400000303983688, 0.1899999976158142, -0.44999998807907104, -0.08799999952316284, 0.36000001430511475, 0.0860000029206276, -0.10999999940395355, -0.01899999938905239, -0.3100000023841858, 0.09099999815225601, -0.10999999940395355, 0.028999999165534973, 0.0010999999940395355, -0.017999999225139618, 0.08100000023841858, 0.020999999716877937, 0.0820000022649765, 0.007499999832361937, 0.23999999463558197, 0.02500000037252903, 0.10000000149011612, 0.06300000101327896]... [Tensor of shape torch.Size([1, 35])]
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([[-1.3984],
        [ 0.5055],
        [-1.2893],
        [ 0.7687],
        [ 1.4874],
        [ 1.2169],
        [-0.0179],
        [ 0.4686],
        [ 1.8998],
        [-1.8617]], 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