DownSyndrome#

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

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

Define clock metadata#

[4]:
model.metadata["clock_name"] = 'downsyndrome'
model.metadata["data_type"] = 'methylation'
model.metadata["species"] = 'Homo sapiens'
model.metadata["year"] = 2021
model.metadata["approved_by_author"] = '⌛'
model.metadata["citation"] = "Muskens, Ivo S., et al. \"Germline aberrant methylation associated with Down syndrome and its impact on childhood acute lymphoblastic leukemia risk.\" Nature Communications 12.1 (2021): 821."
model.metadata["doi"] = "https://doi.org/10.1038/s41467-021-21064-z"
model.metadata["research_only"] = None
model.metadata["notes"] = "Blood DNA-methylation classifier that distinguishes individuals with Down syndrome (trisomy 21) from euploid controls using trisomy-associated differentially methylated CpGs identified from neonatal blood, with top signals at hematopoietic regulators such as RUNX1 and FLI1."
model.metadata["tissue"] = 'neonatal dried blood spots (newborn whole blood)'
model.metadata["predicts"] = 'Down syndrome (trisomy 21) status vs euploid controls'
model.metadata["unit"] = 'score (arbitrary)'
model.metadata["model_type"] = 'Weighted average of CpGs'
model.metadata["platform"] = 'Illumina EPIC'
model.metadata["population"] = 'newborns/neonates (pediatric)'
model.metadata["journal"] = 'Nature Communications'
model.metadata["last_author"] = 'Adam J. de Smith'
model.metadata["n_features"] = 652
model.metadata["citations"] = 62
model.metadata["citations_date"] = '2026-07-05'

Download clock dependencies#

[5]:
os.system(f"curl -sL -o downsyndrome.xlsx https://static-content.springer.com/esm/art%3A10.1038%2Fs41467-021-21064-z/MediaObjects/41467_2021_21064_MOESM6_ESM.xlsx")
[5]:
0

Load features#

[6]:
df = pd.read_excel('downsyndrome.xlsx', sheet_name='EWAS_autosomes', skiprows=2)
model.features = df['CpG'].tolist()
/Users/lucascamillo/pyaging/.venv/lib/python3.13/site-packages/openpyxl/worksheet/_reader.py:329: UserWarning: Unknown extension is not supported and will be removed
  warn(msg)

Load weights into base model#

[7]:
weights = torch.tensor(df['beta_overall'].tolist()).unsqueeze(0).float()
intercept = torch.tensor([0.0]).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': 'Muskens, Ivo S., et al. "Germline aberrant methylation '
             'associated with Down syndrome and its impact on childhood acute '
             'lymphoblastic leukemia risk." Nature Communications 12.1 (2021): '
             '821.',
 'clock_name': 'downsyndrome',
 'data_type': 'methylation',
 'doi': 'https://doi.org/10.1038/s41467-021-21064-z',
 '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: ['cg07741821', 'cg02993069', 'cg12477880', 'cg08882472', 'cg24942416', 'cg07841633', 'cg00994804', 'cg11218872', 'cg02451831', 'cg13382072', 'cg24020235', 'cg17239923', 'cg19030331', 'cg03142697', 'cg24999883', 'cg12679760', 'cg23719650', 'cg11972401', 'cg23565347', 'cg19765472', 'cg04599341', 'cg16831070', 'cg06758350', 'cg11151981', 'cg08620751', 'cg08849601', 'cg02680932', 'cg22539182', 'cg11075561', 'cg04131721']... [Total elements: 652]
base_model_features: None

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

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

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

base_model.linear.weight: [-0.28867992758750916, 0.19754931330680847, 0.38263070583343506, 0.15737323462963104, -0.17506907880306244, -0.3285122215747833, 0.38840898871421814, -0.12085756659507751, -0.15854349732398987, 0.179888516664505, 0.18759849667549133, 0.23218844830989838, 0.16510215401649475, 0.3955685794353485, -0.0671553760766983, 0.18286938965320587, -0.10707408934831619, 0.05787608027458191, -0.09203432500362396, 0.2067182958126068, 0.19878044724464417, -0.061179906129837036, 0.28260132670402527, -0.062310606241226196, 0.1342443823814392, -0.07032307982444763, -0.07384317368268967, -0.14031463861465454, -0.22928495705127716, -0.0856233760714531]... [Tensor of shape torch.Size([1, 652])]
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([[-4.8313],
        [-1.6036],
        [ 4.0192],
        [-1.2427],
        [ 1.9975],
        [-1.7729],
        [ 0.8015],
        [-1.8500],
        [ 1.6546],
        [ 0.3752]], 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: downsyndrome.xlsx