NeuSin#

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

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

Define clock metadata#

[4]:
model.metadata["clock_name"] = 'neusin'
model.metadata["data_type"] = 'methylation'
model.metadata["species"] = 'Homo sapiens'
model.metadata["year"] = 2024
model.metadata["approved_by_author"] = '⌛'
model.metadata["citation"] = "Tong, Huige, et al. \"Cell-type-specific and cell-type-independent DNA methylation clocks.\" Aging 16 (2024)."
model.metadata["doi"] = "https://doi.org/10.18632/aging.206184"
model.metadata["research_only"] = None
model.metadata["notes"] = "Neuron semi-intrinsic DNA-methylation clock estimating chronological age in prefrontal cortex, trained by elastic-net regression on neuron-specific age-associated CpGs identified through cell-type deconvolution but applied to unadjusted methylation values. It captures within-neuron aging and shows age acceleration in Alzheimer's disease."
model.metadata["tissue"] = 'brain (prefrontal cortex, bulk tissue, neuron-specific CpGs)'
model.metadata["predicts"] = 'chronological age'
model.metadata["unit"] = 'years'
model.metadata["model_type"] = 'Elastic net'
model.metadata["platform"] = 'Illumina 450K'
model.metadata["population"] = 'adults (18-97 years)'
model.metadata["journal"] = 'Aging'
model.metadata["last_author"] = 'Andrew E. Teschendorff'
model.metadata["n_features"] = 672
model.metadata["citations"] = 25
model.metadata["citations_date"] = '2026-07-05'

Download clock dependencies#

[5]:
supplementary_url = "https://raw.githubusercontent.com/Duzhaozhen/OmniAge/c10fbe8cb92957520fbff1d55ae1def0691252e5/OmniAgePy/src/omniage/data/CTS/Neu-Sin.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': 'Tong, Huige, et al. "Cell-type-specific and '
             'cell-type-independent DNA methylation clocks." Aging 16 (2024).',
 'clock_name': 'neusin',
 'data_type': 'methylation',
 'doi': 'https://doi.org/10.18632/aging.206184',
 'notes': None,
 'research_only': None,
 'species': 'Homo sapiens',
 'version': None,
 'year': 2024}
reference_values: None
preprocess_name: None
preprocess_dependencies: None
postprocess_name: None
postprocess_dependencies: None
features: ['cg10626816', 'cg13571388', 'cg17826530', 'cg06711298', 'cg08193650', 'cg10442729', 'cg17343483', 'cg20361600', 'cg21185289', 'cg16369288', 'cg22702772', 'cg26856080', 'cg06385118', 'cg18171715', 'cg18586891', 'cg05477834', 'cg15690342', 'cg18635552', 'cg18745317', 'cg25108022', 'cg00537387', 'cg08692175', 'cg25739875', 'cg18048071', 'cg19421584', 'cg22493372', 'cg02324367', 'cg05492433', 'cg16241714', 'cg26003909']... [Total elements: 672]
base_model_features: None

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

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

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

base_model.linear.weight: [0.6255767941474915, 0.00018867039761971682, 1.4650660753250122, -4.989912986755371, 2.8106305599212646, 3.3365237712860107, -8.365673065185547, -7.561515808105469, -2.2176127433776855, 2.238844394683838, 5.353684425354004, 18.882240295410156, -1.537793755531311, 18.469179153442383, 0.3016071319580078, -0.4679134786128998, 0.7296689748764038, -9.179381370544434, 0.04645940288901329, 7.833886623382568, -2.897672414779663, -21.346012115478516, 9.050196647644043, 0.5711203813552856, 0.47357064485549927, 0.11948469281196594, 0.0023688615765422583, -1.3019375801086426, 57.94570541381836, -2.4218344688415527]... [Tensor of shape torch.Size([1, 672])]
base_model.linear.bias: tensor([20.1315])

%==================================== 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([[ -26.3359],
        [ 213.3675],
        [-104.1039],
        [-339.0749],
        [ -66.5274],
        [ 113.9317],
        [ 141.6260],
        [ -65.5180],
        [  -2.5413],
        [-400.5478]], 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