{ "cells": [ { "cell_type": "markdown", "id": "d98099fd", "metadata": {}, "source": [ "# StemTOCvitro" ] }, { "cell_type": "markdown", "id": "2e768463", "metadata": {}, "source": [ "## Index\n", "1. [Instantiate model class](#Instantiate-model-class)\n", "2. [Define clock metadata](#Define-clock-metadata)\n", "3. [Download clock dependencies](#Download-clock-dependencies)\n", "5. [Load features](#Load-features)\n", "6. [Load weights into base model](#Load-weights-into-base-model)\n", "7. [Load reference values](#Load-reference-values)\n", "8. [Load preprocess and postprocess objects](#Load-preprocess-and-postprocess-objects)\n", "10. [Check all clock parameters](#Check-all-clock-parameters)\n", "10. [Basic test](#Basic-test)\n", "11. [Save torch model](#Save-torch-model)\n", "12. [Clear directory](#Clear-directory)" ] }, { "cell_type": "markdown", "id": "3c93398b", "metadata": {}, "source": [ "Let's first import some packages:" ] }, { "cell_type": "code", "execution_count": 1, "id": "68253f85", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:34:41.988486Z", "iopub.status.busy": "2026-07-04T19:34:41.988302Z", "iopub.status.idle": "2026-07-04T19:34:43.875297Z", "shell.execute_reply": "2026-07-04T19:34:43.874841Z" } }, "outputs": [], "source": [ "import os\n", "import inspect\n", "import shutil\n", "import json\n", "import torch\n", "import pandas as pd\n", "import pyaging as pya" ] }, { "cell_type": "markdown", "id": "f89eb2f3", "metadata": {}, "source": [ "## Instantiate model class" ] }, { "cell_type": "code", "execution_count": 2, "id": "a960596b", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:34:43.876910Z", "iopub.status.busy": "2026-07-04T19:34:43.876746Z", "iopub.status.idle": "2026-07-04T19:34:43.879335Z", "shell.execute_reply": "2026-07-04T19:34:43.879008Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "class StemTOCvitro(stemTOC):\n", " pass\n", "\n" ] } ], "source": [ "def print_entire_class(cls):\n", " source = inspect.getsource(cls)\n", " print(source)\n", "\n", "print_entire_class(pya.models.StemTOCvitro)" ] }, { "cell_type": "code", "execution_count": 3, "id": "302a7c18", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:34:43.880651Z", "iopub.status.busy": "2026-07-04T19:34:43.880568Z", "iopub.status.idle": "2026-07-04T19:34:43.882183Z", "shell.execute_reply": "2026-07-04T19:34:43.881906Z" } }, "outputs": [], "source": [ "model = pya.models.StemTOCvitro()" ] }, { "cell_type": "markdown", "id": "5d13953b", "metadata": {}, "source": [ "## Define clock metadata" ] }, { "cell_type": "code", "execution_count": 4, "id": "35a15e9a", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:34:43.883351Z", "iopub.status.busy": "2026-07-04T19:34:43.883283Z", "iopub.status.idle": "2026-07-04T19:34:43.885411Z", "shell.execute_reply": "2026-07-04T19:34:43.885027Z" } }, "outputs": [], "source": [ "model.metadata[\"clock_name\"] = \"stemtocvitro\"\n", "model.metadata[\"data_type\"] = \"DNA methylation\" # Paper: The study constructs clocks from DNA methylation measurements.\n", "model.metadata[\"species\"] = \"Homo sapiens\" # Paper: The analyzed samples and clock are human.\n", "model.metadata[\"year\"] = 2024\n", "model.metadata[\"approved_by_author\"] = \"⌛\"\n", "model.metadata[\"citation\"] = \"Zhu, Tianlei, et al. \\\"An improved epigenetic counter to track mitotic age in cells.\\\" Nature Communications 15 (2024): 4211.\"\n", "model.metadata[\"doi\"] = \"https://doi.org/10.1038/s41467-024-48649-8\"\n", "model.metadata[\"notes\"] = \"In-vitro precursor of stemTOC based on the 95th percentile across 629 population-doubling-associated CpGs.\"\n", "model.metadata[\"research_only\"] = None\n", "model.metadata[\"tissue\"] = [\"multi-tissue\", \"cultured human cells\"] # Paper: Feature selection used fetal/neonatal reference tissues and cultured normal cell types; stemTOC also used blood cohorts.\n", "model.metadata[\"predicts\"] = [\"mitotic age\"] # Paper: The paper describes the returned score as relative mitotic age.\n", "model.metadata[\"training_target\"] = [\"population doublings\"] # Paper: Candidate CpGs were selected for methylation gain with population doublings and, where applicable, age in blood.\n", "model.metadata[\"unit\"] = [\"beta value\"] # Paper: The score is the 95% upper quantile of CpG DNAm beta values.\n", "model.metadata[\"model_type\"] = \"95th-percentile methylation aggregation\" # Paper: The score is computed as the 95% upper quantile across selected CpGs.\n", "model.metadata[\"platform\"] = [\"Illumina 450K\", \"Illumina EPIC\"] # Paper: Derivation datasets included 450K fetal samples and EPIC cultured-cell samples.\n", "model.metadata[\"population\"] = \"prenatal and newborn\" # Paper: The derivation cohorts are fetal/neonatal tissues, normal cell cultures, and for stemTOC adult blood cohorts.\n", "model.metadata[\"journal\"] = \"Nature Communications\"\n", "model.metadata[\"last_author\"] = \"Andrew E. Teschendorff\"\n", "model.metadata[\"n_features\"] = 629\n", "model.metadata[\"citations\"] = 24\n", "model.metadata[\"citations_date\"] = \"2026-07-05\"\n" ] }, { "cell_type": "markdown", "id": "94b38fbd", "metadata": {}, "source": [ "## Download clock dependencies" ] }, { "cell_type": "code", "execution_count": 5, "id": "f8ffb424", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:34:43.886594Z", "iopub.status.busy": "2026-07-04T19:34:43.886525Z", "iopub.status.idle": "2026-07-04T19:34:44.162319Z", "shell.execute_reply": "2026-07-04T19:34:44.161610Z" } }, "outputs": [ { "data": { "text/plain": [ "0" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "supplementary_url = \"https://raw.githubusercontent.com/Duzhaozhen/OmniAge/c10fbe8cb92957520fbff1d55ae1def0691252e5/OmniAgePy/src/omniage/data/StemTOCvitro.csv\"\n", "supplementary_file_name = \"coefficients.csv\"\n", "os.system(f\"curl -sL -o {supplementary_file_name} {supplementary_url}\")" ] }, { "cell_type": "markdown", "id": "46faed2e", "metadata": {}, "source": [ "## Load features" ] }, { "cell_type": "code", "execution_count": 6, "id": "d7cc4659", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:34:44.164789Z", "iopub.status.busy": "2026-07-04T19:34:44.164593Z", "iopub.status.idle": "2026-07-04T19:34:44.172169Z", "shell.execute_reply": "2026-07-04T19:34:44.171496Z" } }, "outputs": [], "source": [ "df = pd.read_csv('coefficients.csv')\n", "if str(df.columns[0]).startswith('Unnamed'):\n", " df = df.iloc[:, 1:]\n", "model.features = df['probe'].tolist()" ] }, { "cell_type": "markdown", "id": "1bd735e7", "metadata": {}, "source": [ "## Load weights into base model" ] }, { "cell_type": "code", "execution_count": 7, "id": "86132fef", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:34:44.174045Z", "iopub.status.busy": "2026-07-04T19:34:44.173887Z", "iopub.status.idle": "2026-07-04T19:34:44.176727Z", "shell.execute_reply": "2026-07-04T19:34:44.175989Z" } }, "outputs": [], "source": [ "weights = torch.tensor([1.0]).unsqueeze(0)\n", "intercept = torch.tensor([0.0])" ] }, { "cell_type": "code", "execution_count": 8, "id": "556797de", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:34:44.178441Z", "iopub.status.busy": "2026-07-04T19:34:44.178281Z", "iopub.status.idle": "2026-07-04T19:34:44.181691Z", "shell.execute_reply": "2026-07-04T19:34:44.181030Z" } }, "outputs": [], "source": [ "base_model = pya.models.LinearModel(input_dim=len(model.features))\n", "\n", "base_model.linear.weight.data = weights.float()\n", "base_model.linear.bias.data = intercept.float()\n", "\n", "model.base_model = base_model" ] }, { "cell_type": "markdown", "id": "1d5f9e4f", "metadata": {}, "source": [ "## Load reference values" ] }, { "cell_type": "code", "execution_count": 9, "id": "21a23bd7", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:34:44.183360Z", "iopub.status.busy": "2026-07-04T19:34:44.183239Z", "iopub.status.idle": "2026-07-04T19:34:44.185467Z", "shell.execute_reply": "2026-07-04T19:34:44.184918Z" } }, "outputs": [], "source": [ "model.reference_values = [-1]*len(model.features)" ] }, { "cell_type": "markdown", "id": "a207b9ef", "metadata": {}, "source": [ "## Load preprocess and postprocess objects" ] }, { "cell_type": "code", "execution_count": 10, "id": "88c05f98", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:34:44.187290Z", "iopub.status.busy": "2026-07-04T19:34:44.187160Z", "iopub.status.idle": "2026-07-04T19:34:44.189586Z", "shell.execute_reply": "2026-07-04T19:34:44.189134Z" } }, "outputs": [], "source": [ "model.preprocess_name = \"0.95 quantile\"\n", "model.preprocess_dependencies = None" ] }, { "cell_type": "code", "execution_count": 11, "id": "1636e3dd", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:34:44.191384Z", "iopub.status.busy": "2026-07-04T19:34:44.191247Z", "iopub.status.idle": "2026-07-04T19:34:44.193184Z", "shell.execute_reply": "2026-07-04T19:34:44.192701Z" } }, "outputs": [], "source": [ "model.postprocess_name = None\n", "model.postprocess_dependencies = None" ] }, { "cell_type": "markdown", "id": "c2fe33f5", "metadata": {}, "source": [ "## Check all clock parameters" ] }, { "cell_type": "code", "execution_count": 12, "id": "ad9e9b16", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:34:44.194748Z", "iopub.status.busy": "2026-07-04T19:34:44.194636Z", "iopub.status.idle": "2026-07-04T19:34:44.198601Z", "shell.execute_reply": "2026-07-04T19:34:44.198060Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "%==================================== Model Details ====================================%\n", "Model Attributes:\n", "\n", "training: True\n", "metadata: {'approved_by_author': '⌛',\n", " 'citation': 'Zhu, Tianyu, et al. \"A pan-tissue DNA methylation atlas enables '\n", " 'in silico decomposition of human tissue methylomes at cell-type '\n", " 'resolution.\" Nature Communications 15 (2024).',\n", " 'clock_name': 'stemtocvitro',\n", " 'data_type': 'methylation',\n", " 'doi': 'https://doi.org/10.1038/s41467-024-48649-8',\n", " 'notes': None,\n", " 'research_only': None,\n", " 'species': 'Homo sapiens',\n", " 'version': None,\n", " 'year': 2024}\n", "reference_values: [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1]... [Total elements: 629]\n", "preprocess_name: '0.95 quantile'\n", "preprocess_dependencies: None\n", "postprocess_name: None\n", "postprocess_dependencies: None\n", "features: ['cg20327258', 'cg23062112', 'cg07365816', 'cg08659394', 'cg14575559', 'cg13294856', 'cg18560328', 'cg21229268', 'cg20078466', 'cg23091824', 'cg03865257', 'cg16443455', 'cg11250773', 'cg10687823', 'cg12892303', 'cg12781700', 'cg13583934', 'cg12065366', 'cg25203031', 'cg17404915', 'cg22299454', 'cg10698404', 'cg09097345', 'cg05404701', 'cg24010885', 'cg17712694', 'cg20707222', 'cg08901752', 'cg11297107', 'cg17876581']... [Total elements: 629]\n", "base_model_features: None\n", "\n", "%==================================== Model Details ====================================%\n", "Model Structure:\n", "\n", "base_model: LinearModel(\n", " (linear): Linear(in_features=629, out_features=1, bias=True)\n", ")\n", "\n", "%==================================== Model Details ====================================%\n", "Model Parameters and Weights:\n", "\n", "base_model.linear.weight: tensor([[1.]])\n", "base_model.linear.bias: tensor([0.])\n", "\n", "%==================================== Model Details ====================================%\n", "\n" ] } ], "source": [ "pya.utils.print_model_details(model)" ] }, { "cell_type": "markdown", "id": "2f6d1733", "metadata": {}, "source": [ "## Basic test" ] }, { "cell_type": "code", "execution_count": 13, "id": "a2461127", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:34:44.200005Z", "iopub.status.busy": "2026-07-04T19:34:44.199909Z", "iopub.status.idle": "2026-07-04T19:34:44.217490Z", "shell.execute_reply": "2026-07-04T19:34:44.217008Z" } }, "outputs": [ { "data": { "text/plain": [ "tensor([[1.8129],\n", " [1.7694],\n", " [1.5825],\n", " [1.5507],\n", " [1.6496],\n", " [1.5994],\n", " [1.6658],\n", " [1.6827],\n", " [1.6054],\n", " [1.7836]], dtype=torch.float64, grad_fn=)" ] }, "execution_count": 13, "metadata": {}, "output_type": "execute_result" } ], "source": [ "torch.manual_seed(42)\n", "input = torch.randn(10, len(model.features), dtype=float)\n", "model.eval()\n", "model.to(float)\n", "pred = model(input)\n", "pred" ] }, { "cell_type": "markdown", "id": "81ce6867", "metadata": {}, "source": [ "## Save torch model" ] }, { "cell_type": "code", "execution_count": 14, "id": "e397d341", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:34:44.218795Z", "iopub.status.busy": "2026-07-04T19:34:44.218698Z", "iopub.status.idle": "2026-07-04T19:34:44.222110Z", "shell.execute_reply": "2026-07-04T19:34:44.221816Z" } }, "outputs": [], "source": [ "torch.save(model, f\"../weights/{model.metadata['clock_name']}.pt\")" ] }, { "cell_type": "markdown", "id": "742514a1", "metadata": {}, "source": [ "## Clear directory\n", "" ] }, { "cell_type": "code", "execution_count": 15, "id": "a5ac5c01", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:34:44.223540Z", "iopub.status.busy": "2026-07-04T19:34:44.223471Z", "iopub.status.idle": "2026-07-04T19:34:44.226987Z", "shell.execute_reply": "2026-07-04T19:34:44.226615Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Deleted file: coefficients.csv\n" ] } ], "source": [ "# Function to remove a folder and all its contents\n", "def remove_folder(path):\n", " try:\n", " shutil.rmtree(path)\n", " print(f\"Deleted folder: {path}\")\n", " except Exception as e:\n", " print(f\"Error deleting folder {path}: {e}\")\n", "\n", "# Get a list of all files and folders in the current directory\n", "all_items = os.listdir('.')\n", "\n", "# Loop through the items\n", "for item in all_items:\n", " # Check if it's a file and does not end with .ipynb\n", " if os.path.isfile(item) and not item.endswith('.ipynb'):\n", " os.remove(item)\n", " print(f\"Deleted file: {item}\")\n", " # Check if it's a folder\n", " elif os.path.isdir(item):\n", " remove_folder(item)" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.13.11" } }, "nbformat": 4, "nbformat_minor": 5 }