RepliTali#

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

    def preprocess(self, x):
        return x

    def postprocess(self, x):
        return x

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

Define clock metadata#

[4]:
model.metadata["clock_name"] = 'replitali'
model.metadata["data_type"] = 'methylation'
model.metadata["species"] = 'Homo sapiens'
model.metadata["year"] = 2022
model.metadata["approved_by_author"] = '⌛'
model.metadata["citation"] = "Endicott, Jamie L., et al. \"Cell division drives DNA methylation loss in late-replicating domains in primary human cells.\" Nature Communications 13.1 (2022): 6659."
model.metadata["doi"] = "https://doi.org/10.1038/s41467-022-34268-8"
model.metadata["research_only"] = None
model.metadata["notes"] = None

Download clock dependencies#

Download GitHub repository#

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

Load features#

From CSV file#

[6]:
df = pd.read_csv('Nature_Comm_2022/RepliTali/RepliTali_coefs.csv')
df['feature'] = df['Coefficient']
df['coefficient'] = df['Value']

model.features = df['feature'][1:].tolist()

Load weights into base model#

[7]:
weights = torch.tensor(df['coefficient'][1:].tolist()).unsqueeze(0)
intercept = torch.tensor([df['coefficient'][0]])

Linear model#

[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': 'Endicott, Jamie L., et al. "Cell division drives DNA methylation '
             'loss in late-replicating domains in primary human cells." Nature '
             'Communications 13.1 (2022): 6659.',
 'clock_name': 'replitali',
 'data_type': 'methylation',
 'doi': 'https://doi.org/10.1038/s41467-022-34268-8',
 'notes': None,
 'research_only': None,
 'species': 'Homo sapiens',
 'version': None,
 'year': 2022}
reference_values: None
preprocess_name: None
preprocess_dependencies: None
postprocess_name: None
postprocess_dependencies: None
features: ['cg00077044', 'cg00150168', 'cg00454443', 'cg00495856', 'cg01616440', 'cg02137583', 'cg02220491', 'cg02392915', 'cg02583589', 'cg03179540', 'cg03421046', 'cg03786165', 'cg03988540', 'cg04155630', 'cg04390831', 'cg04698728', 'cg05635798', 'cg05662956', 'cg05898730', 'cg06001519', 'cg06003656', 'cg06029627', 'cg06113963', 'cg06417611', 'cg06530442', 'cg06725108', 'cg06792538', 'cg06944758', 'cg07724309', 'cg08111618']... [Total elements: 87]
base_model_features: None

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

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

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

base_model.linear.weight: [-0.37647414207458496, -4.204704761505127, -1.413773775100708, -1.72621750831604, -0.07973441481590271, 8.181479454040527, -0.024885866791009903, -5.290876865386963, -0.03167755529284477, -2.6441094875335693, -0.7813723087310791, -0.9527625441551208, 3.7167017459869385, -0.09135447442531586, -0.024930506944656372, -6.9897050857543945, -1.5100187063217163, -0.06429270654916763, -2.511181354522705, 2.800859212875366, 2.344932794570923, -0.000938242010306567, -8.189630508422852, -2.3566792011260986, -3.3855528831481934, -4.197580814361572, -0.6439054608345032, -6.865860462188721, 0.1207914724946022, -0.00893024355173111]... [Tensor of shape torch.Size([1, 87])]
base_model.linear.bias: tensor([101.5896])

%==================================== 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([[133.0796],
        [204.0084],
        [118.1621],
        [ 37.6353],
        [ 79.4020],
        [134.4028],
        [166.1542],
        [ 18.4314],
        [ 38.6508],
        [100.6297]], 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 folder: Nature_Comm_2022