DepressionBarbu#

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.DepressionBarbu)
class DepressionBarbu(pyagingModel):
    def __init__(self):
        super().__init__()

    def preprocess(self, x):
        return x

    def postprocess(self, x):
        return x

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

Define clock metadata#

[4]:
model.metadata["clock_name"] = 'depressionbarbu'
model.metadata["data_type"] = 'methylation'
model.metadata["species"] = 'Homo sapiens'
model.metadata["year"] = 2021
model.metadata["approved_by_author"] = '⌛'
model.metadata["citation"] = "Barbu, Miruna C., et al. \"Epigenetic prediction of major depressive disorder.\" Molecular Psychiatry 26.9 (2021): 5112-5123."
model.metadata["doi"] = "https://doi.org/10.1038/s41380-020-0808-3"
model.metadata["research_only"] = None
model.metadata["notes"] = "Blood methylation risk score for major depressive disorder built with penalised regression on genome-wide EPIC-array CpGs, trained on over 1,200 cases and 1,800 controls. Discriminates prevalent from incident MDD independently of polygenic risk, with a smoking-independent variant also derived."
model.metadata["tissue"] = 'whole blood'
model.metadata["predicts"] = 'major depressive disorder (MDD) status/risk'
model.metadata["unit"] = 'score (arbitrary)'
model.metadata["model_type"] = 'Elastic net'
model.metadata["platform"] = 'Illumina EPIC'
model.metadata["population"] = 'adults (Generation Scotland cohort)'
model.metadata["journal"] = 'Molecular Psychiatry'
model.metadata["last_author"] = 'Andrew M. McIntosh'
model.metadata["n_features"] = 196
model.metadata["citations"] = 93
model.metadata["citations_date"] = '2026-07-05'

Download clock dependencies#

[5]:
os.system(f"curl -sL -o depressionbarbu.xlsx https://static-content.springer.com/esm/art%3A10.1038%2Fs41380-020-0808-3/MediaObjects/41380_2020_808_MOESM4_ESM.xlsx")
[5]:
0

Load features#

[6]:
df = pd.read_excel('depressionbarbu.xlsx', sheet_name='MRS - CpG sites and weights')
model.features = df['CpG site'].tolist()

Load weights into base model#

[7]:
weights = torch.tensor(df['Beta'].tolist()).unsqueeze(0).float()
# Methylation risk score calibration intercept
intercept = torch.tensor([12.2169841]).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': 'Barbu, Miruna C., et al. "Epigenetic prediction of major '
             'depressive disorder." Molecular Psychiatry 26.9 (2021): '
             '5112-5123.',
 'clock_name': 'depressionbarbu',
 'data_type': 'methylation',
 'doi': 'https://doi.org/10.1038/s41380-020-0808-3',
 '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: ['cg02115394', 'cg15971980', 'cg03054303', 'cg09791621', 'cg12736206', 'cg22225420', 'cg22407822', 'cg02998018', 'cg07459409', 'cg20496693', 'cg15251779', 'cg03070922', 'cg04142555', 'cg18090197', 'cg14728380', 'cg09929180', 'cg13529291', 'cg19474047', 'cg04191989', 'cg03607825', 'cg05575921', 'cg03307749', 'cg12832498', 'cg10623600', 'cg15847996', 'cg25242471', 'cg10928544', 'cg02636222', 'cg08464831', 'cg15586193']... [Total elements: 196]
base_model_features: None

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

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

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

base_model.linear.weight: [0.13174669444561005, 0.017368832603096962, 0.07059700042009354, -0.018956167623400688, 0.35600546002388, 0.2889443039894104, 0.0505455806851387, -0.4532535970211029, -0.2310783565044403, 0.006119664758443832, -0.07810869812965393, 0.0040334537625312805, 0.005831866059452295, 0.21422632038593292, 0.07561899721622467, 0.13462267816066742, 0.37971192598342896, -0.21138310432434082, 0.1820078045129776, 0.06565909832715988, -0.14514309167861938, -0.3468712866306305, 0.13083887100219727, 0.03079209290444851, -0.06906116753816605, 0.11012744158506393, 0.01911790855228901, 0.5892500281333923, -0.025107210502028465, -0.22120502591133118]... [Tensor of shape torch.Size([1, 196])]
base_model.linear.bias: tensor([12.2170])

%==================================== 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([[11.7817],
        [12.6549],
        [11.4798],
        [12.3791],
        [11.4735],
        [ 7.2415],
        [18.4420],
        [14.8113],
        [14.2788],
        [13.7944]], 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: depressionbarbu.xlsx