Pasta#
Index#
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.Pasta)
class Pasta(pyagingModel):
def __init__(self):
super().__init__()
@staticmethod
def _rank_average(values):
"""
Assign average ranks (1-based) per vector, handling ties.
"""
sorted_vals, sorted_idx = torch.sort(values)
ranks = torch.empty_like(sorted_vals, dtype=values.dtype)
n = values.numel()
start = 0
while start < n:
end = start + 1
while end < n and sorted_vals[end] == sorted_vals[start]:
end += 1
avg_rank = (start + end - 1) / 2.0 + 1.0
ranks[sorted_idx[start:end]] = avg_rank
start = end
return ranks
def preprocess(self, x):
"""
Fill missing values with the global median then rank-normalize per sample.
"""
median = torch.nanmedian(x)
if torch.isnan(median):
median = torch.tensor(0.0, device=x.device, dtype=x.dtype)
x = torch.where(torch.isnan(x), median, x)
ranked = torch.empty_like(x, dtype=x.dtype)
for i in range(x.size(0)):
ranked[i] = self._rank_average(x[i])
return ranked
def postprocess(self, x):
"""
Apply linear scaling and shifting constants from the original Pasta definition.
"""
scale = self.postprocess_dependencies[0]
offset_factor = self.postprocess_dependencies[1]
return x * scale + offset_factor * scale
[3]:
model = pya.models.Pasta()
Define clock metadata#
[4]:
model.metadata["clock_name"] = 'pasta'
model.metadata["data_type"] = 'transcriptomics'
model.metadata["species"] = 'Homo sapiens'
model.metadata["year"] = 2025
model.metadata["approved_by_author"] = '✅'
model.metadata["citation"] = "Salignon, Jerome, et al. \"Pasta, an age-shift transcriptomic clock, maps the chemical and genetic determinants of aging and rejuvenation.\" bioRxiv (2025): 2025-06."
model.metadata["doi"] = "https://doi.org/10.1101/2025.06.04.657785"
model.metadata["research_only"] = None
model.metadata["notes"] = "Rank-normalized transcriptomic clock."
Download clock dependencies#
Download coefficient file#
[5]:
coeff_url = "https://raw.githubusercontent.com/bio-learn/biolearn/master/biolearn/data/Pasta.csv"
os.system(f"curl -L {coeff_url} -o Pasta.csv")
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 322k 100 322k 0 0 1174k 0 --:--:-- --:--:-- --:--:-- 1176k
[5]:
0
Load features#
From CSV file#
[6]:
coeffs = pd.read_csv('Pasta.csv')
coeffs['feature'] = coeffs['GeneID']
coeffs['coefficient'] = coeffs['CoefficientTraining']
model.features = coeffs['feature'].tolist()
Load weights into base model#
From CSV file#
[7]:
weights = torch.tensor(coeffs['coefficient'].tolist()).unsqueeze(0)
intercept = torch.tensor([0.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 = [float("nan")] * len(model.features)
Load preprocess and postprocess objects#
[10]:
model.preprocess_name = "median_fill_and_rank_normalization"
model.preprocess_dependencies = None
[11]:
model.postprocess_name = "scale_and_shift"
model.postprocess_dependencies = [-4.76348378687217, -0.0502893445253186]
Check all clock parameters#
[12]:
pya.utils.print_model_details(model)
%==================================== Model Details ====================================%
Model Attributes:
training: True
metadata: {'approved_by_author': '✅',
'citation': 'Salignon, Jerome, et al. "Pasta, an age-shift transcriptomic '
'clock, maps the chemical and genetic determinants of aging and '
'rejuvenation." bioRxiv (2025): 2025-06.',
'clock_name': 'pasta',
'data_type': 'transcriptomics',
'doi': 'https://doi.org/10.1101/2025.06.04.657785',
'notes': 'Rank-normalized transcriptomic clock.',
'research_only': None,
'species': 'Homo sapiens',
'version': None,
'year': 2025}
reference_values: [nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan]... [Total elements: 8113]
preprocess_name: 'median_fill_and_rank_normalization'
preprocess_dependencies: None
postprocess_name: 'scale_and_shift'
postprocess_dependencies: [-4.76348378687217, -0.0502893445253186]
features: ['ENSG00000196839', 'ENSG00000170558', 'ENSG00000133997', 'ENSG00000168060', 'ENSG00000101473', 'ENSG00000136754', 'ENSG00000113552', 'ENSG00000177485', 'ENSG00000136560', 'ENSG00000094631', 'ENSG00000108840', 'ENSG00000170248', 'ENSG00000153094', 'ENSG00000159921', 'ENSG00000165879', 'ENSG00000135451', 'ENSG00000142892', 'ENSG00000179776', 'ENSG00000167670', 'ENSG00000129484', 'ENSG00000041880', 'ENSG00000113361', 'ENSG00000141198', 'ENSG00000100284', 'ENSG00000013619', 'ENSG00000010017', 'ENSG00000105993', 'ENSG00000113810', 'ENSG00000182963', 'ENSG00000126261']... [Total elements: 8113]
base_model_features: None
%==================================== Model Details ====================================%
Model Structure:
base_model: LinearModel(
(linear): Linear(in_features=8113, out_features=1, bias=True)
)
%==================================== Model Details ====================================%
Model Parameters and Weights:
base_model.linear.weight: [-2.4399256290053017e-05, -1.774273368937429e-05, 1.554851587570738e-05, 1.1031659596483223e-05, 1.6993128156173043e-05, 3.9308954001171514e-05, -0.00012627331307157874, 2.8949250463483622e-06, -6.271281017689034e-05, 2.9893646569689736e-05, 3.6174697015667334e-05, 6.864466558909044e-05, -2.3814825908630155e-05, 3.11008479911834e-05, 1.0880126865231432e-05, 9.605172635929193e-06, 1.1990639904979616e-05, 9.29949510464212e-06, 6.331568147288635e-05, -3.362866482348181e-05, -0.00022874546993989497, -2.7509766368893906e-05, 6.674586074950639e-06, 1.986255301744677e-05, -3.5506527638062835e-05, 2.922421663242858e-05, -4.5067787141306326e-05, 5.991863872623071e-05, 3.728850060724653e-05, 4.235586311551742e-05]... [Tensor of shape torch.Size([1, 8113])]
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([[-12.0950],
[-36.7366],
[ 2.5806],
[ 29.9285],
[-21.5258],
[ -3.6489],
[-39.3746],
[ 36.6380],
[ 27.4081],
[-33.9218]], dtype=torch.float64, grad_fn=<AddBackward0>)
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: EPIC_salas_18_reference.csv
Deleted file: Pasta.csv