Template#

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:

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

Instantiate model class#

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

print_entire_class(pya.models.Template)
[ ]:
model = pya.models.Template()

Define clock metadata#

[ ]:
model.metadata["clock_name"] = 'example'
model.metadata["data_type"] = 'methylation'
model.metadata["species"] = 'Homo sapiens'
model.metadata["year"] = 2023
model.metadata["approved_by_author"] = '⌛'
model.metadata["citation"] = "citation"
model.metadata["doi"] = 'doi'
model.metadata["research_only"] = None
model.metadata["notes"] = None

Download clock dependencies#

Download directly with curl#

[ ]:
supplementary_url = "example_url.com"
supplementary_file_name = "example.xlsx"
os.system(f"curl -o {supplementary_file_name} {supplementary_url}")

Download GitHub repository#

[ ]:
github_url = "https://github.com/example/example_github.git"
github_folder_name = github_url.split('/')[-1].split('.')[0]
os.system(f"git clone {github_url}")

Download from R package#

[ ]:
%%writefile download.r

options(repos = c(CRAN = "https://cloud.r-project.org/"))
library(jsonlite)

install.packages("devtools")
devtools::install_github("example/example", build_vignettes = FALSE)
library(example)

write_json(example_object, "example.json", digits = 9)
[ ]:
os.system("Rscript download.r")

Load features#

From Excel file#

[ ]:
model.features = pd.read_excel('example.xlsx', sheet_name='example_sheet', nrows=100)

From CSV file#

[ ]:
model.features = pd.read_csv('example.csv', skiprows=0)

From JSON file#

[ ]:
with open('features.json', 'r') as f:
    features_dict = json.load(f)[0]
model.features = features_dict['template']

Load weights into base model#

From Excel file#

[ ]:
weights = pd.read_excel('example.xlsx', sheet_name='example_sheet', nrows=100)

From CSV file#

[ ]:
weights = pd.read_csv('example.csv', skiprows=0)

From JSON file#

[ ]:
with open('weights.json', 'r') as f:
    weights_dict = json.load(f)[0]

Linear model#

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

PC linear model#

[ ]:
base_model = pya.models.PCLinearModel(input_dim=len(model.features), pc_dim=rotation.shape[1])

base_model.center.data = center.float()
base_model.rotation.data = rotation.float()
base_model.linear.weight.data = weights.float()
base_model.linear.bias.data = intercept.float()

model.base_model = base_model

Load reference values#

[ ]:
model.reference_values = None

From Excel file#

[ ]:
model.reference_values = pd.read_excel('example.xlsx', sheet_name='example_sheet', nrows=100)

From CSV file#

[ ]:
model.reference_values = pd.read_csv('example.csv', skiprows=0)

From JSON file#

[ ]:
with open('reference_values.json', 'r') as f:
    reference_values_dict = json.load(f)[0]
model.reference_values = reference_values_dict['template']

Load preprocess and postprocess objects#

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

Check all clock parameters#

[ ]:
pya.utils.print_model_details(model)

Basic test#

[ ]:
torch.manual_seed(42)
input = torch.randn(10, len(model.features), dtype=float)
model.eval()
model.to(float)
pred = model(input)
pred

Save torch model#

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

Clear directory#

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