{ "cells": [ { "cell_type": "markdown", "id": "a7bdb3d1", "metadata": {}, "source": [ "# CTSLiver" ] }, { "cell_type": "markdown", "id": "ebf0a716", "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": "e45a86f6", "metadata": {}, "source": [ "Let's first import some packages:" ] }, { "cell_type": "code", "execution_count": 1, "id": "63bed9f9", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:34:29.239268Z", "iopub.status.busy": "2026-07-04T19:34:29.239147Z", "iopub.status.idle": "2026-07-04T19:34:31.361432Z", "shell.execute_reply": "2026-07-04T19:34:31.360924Z" } }, "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": "4efcc0da", "metadata": {}, "source": [ "## Instantiate model class" ] }, { "cell_type": "code", "execution_count": 2, "id": "196224ce", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:34:31.363098Z", "iopub.status.busy": "2026-07-04T19:34:31.362913Z", "iopub.status.idle": "2026-07-04T19:34:31.365661Z", "shell.execute_reply": "2026-07-04T19:34:31.365306Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "class CTSLiver(LinearReferenceClock):\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.CTSLiver)" ] }, { "cell_type": "code", "execution_count": 3, "id": "f9ac34fa", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:34:31.366972Z", "iopub.status.busy": "2026-07-04T19:34:31.366890Z", "iopub.status.idle": "2026-07-04T19:34:31.368669Z", "shell.execute_reply": "2026-07-04T19:34:31.368266Z" } }, "outputs": [], "source": [ "model = pya.models.CTSLiver()" ] }, { "cell_type": "markdown", "id": "467b5800", "metadata": {}, "source": [ "## Define clock metadata" ] }, { "cell_type": "code", "execution_count": 4, "id": "d9f4d92a", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:34:31.370082Z", "iopub.status.busy": "2026-07-04T19:34:31.369972Z", "iopub.status.idle": "2026-07-04T19:34:31.372236Z", "shell.execute_reply": "2026-07-04T19:34:31.371834Z" } }, "outputs": [], "source": [ "model.metadata[\"clock_name\"] = \"ctsliver\"\n", "model.metadata[\"data_type\"] = \"DNA methylation\" # Paper: The model is based on DNA methylation measurements.\n", "model.metadata[\"species\"] = \"Homo sapiens\" # Paper: The study samples are Homo sapiens.\n", "model.metadata[\"year\"] = 2024\n", "model.metadata[\"approved_by_author\"] = \"⌛\"\n", "model.metadata[\"citation\"] = \"Tong, Huige, et al. \\\"Cell-type specific epigenetic clocks to quantify biological age at cell-type resolution.\\\" Aging 16 (2024): 14204–14237.\"\n", "model.metadata[\"doi\"] = \"https://doi.org/10.18632/aging.206184\"\n", "model.metadata[\"notes\"] = \"LiverClock is a liver tissue-specific chronological-age clock trained by lasso on age-associated CpGs identified after adjustment for five estimated liver cell fractions; unlike HepClock, it is not hepatocyte-specific.\"\n", "model.metadata[\"research_only\"] = None\n", "model.metadata[\"tissue\"] = [\"liver\"] # Paper: The listed tissue is the model-development sample material.\n", "model.metadata[\"predicts\"] = [\"chronological age\"] # Paper: The reported predictor output is chronological age.\n", "model.metadata[\"training_target\"] = [\"chronological age\"] # Paper: The fitting outcome is chronological age.\n", "model.metadata[\"unit\"] = [\"years\"] # Paper: The returned construct is expressed as years.\n", "model.metadata[\"model_type\"] = \"LASSO regression\" # Paper: The clock was fitted using LASSO.\n", "model.metadata[\"platform\"] = [\"Illumina EPIC\"] # Paper: Training/selection used Illumina EPIC.\n", "model.metadata[\"population\"] = \"adults\" # Paper: adults aged 18–75 years (210 normal liver samples)\n", "model.metadata[\"journal\"] = \"Aging\"\n", "model.metadata[\"last_author\"] = \"Andrew E. Teschendorff\"\n", "model.metadata[\"n_features\"] = 90\n", "model.metadata[\"citations\"] = 25\n", "model.metadata[\"citations_date\"] = \"2026-07-05\"\n" ] }, { "cell_type": "markdown", "id": "934e0cc9", "metadata": {}, "source": [ "## Download clock dependencies" ] }, { "cell_type": "code", "execution_count": 5, "id": "aea5418c", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:34:31.373566Z", "iopub.status.busy": "2026-07-04T19:34:31.373484Z", "iopub.status.idle": "2026-07-04T19:34:31.677657Z", "shell.execute_reply": "2026-07-04T19:34:31.677017Z" } }, "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/CTS/Liver.csv\"\n", "supplementary_file_name = \"coefficients.csv\"\n", "os.system(f\"curl -sL -o {supplementary_file_name} {supplementary_url}\")" ] }, { "cell_type": "markdown", "id": "3aa5a0bc", "metadata": {}, "source": [ "## Load features" ] }, { "cell_type": "code", "execution_count": 6, "id": "112adec2", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:34:31.679896Z", "iopub.status.busy": "2026-07-04T19:34:31.679728Z", "iopub.status.idle": "2026-07-04T19:34:31.686351Z", "shell.execute_reply": "2026-07-04T19:34:31.685767Z" } }, "outputs": [], "source": [ "df = pd.read_csv('coefficients.csv')\n", "if str(df.columns[0]).startswith('Unnamed'):\n", " df = df.iloc[:, 1:]\n", "mask = df['probe'].astype(str).str.lower().isin(['intercept', '(intercept)'])\n", "intercept_value = float(df.loc[mask, 'coef'].iloc[0]) if mask.any() else 0.0\n", "coef_df = df.loc[~mask].reset_index(drop=True)\n", "model.features = coef_df['probe'].tolist()" ] }, { "cell_type": "markdown", "id": "3f1902b3", "metadata": {}, "source": [ "## Load weights into base model" ] }, { "cell_type": "code", "execution_count": 7, "id": "c5b61450", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:34:31.688199Z", "iopub.status.busy": "2026-07-04T19:34:31.688071Z", "iopub.status.idle": "2026-07-04T19:34:31.690884Z", "shell.execute_reply": "2026-07-04T19:34:31.690311Z" } }, "outputs": [], "source": [ "weights = torch.tensor(coef_df['coef'].tolist()).unsqueeze(0).float()\n", "intercept = torch.tensor([intercept_value]).float()" ] }, { "cell_type": "code", "execution_count": 8, "id": "1a213d37", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:34:31.692541Z", "iopub.status.busy": "2026-07-04T19:34:31.692414Z", "iopub.status.idle": "2026-07-04T19:34:31.695167Z", "shell.execute_reply": "2026-07-04T19:34:31.694699Z" } }, "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": "8208c199", "metadata": {}, "source": [ "## Load reference values" ] }, { "cell_type": "code", "execution_count": 9, "id": "449d036b", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:34:31.696883Z", "iopub.status.busy": "2026-07-04T19:34:31.696768Z", "iopub.status.idle": "2026-07-04T19:34:31.698774Z", "shell.execute_reply": "2026-07-04T19:34:31.698298Z" } }, "outputs": [], "source": [ "model.reference_values = None" ] }, { "cell_type": "markdown", "id": "eeb6fbe6", "metadata": {}, "source": [ "## Load preprocess and postprocess objects" ] }, { "cell_type": "code", "execution_count": 10, "id": "0f0e241f", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:34:31.700387Z", "iopub.status.busy": "2026-07-04T19:34:31.700273Z", "iopub.status.idle": "2026-07-04T19:34:31.702368Z", "shell.execute_reply": "2026-07-04T19:34:31.701765Z" } }, "outputs": [], "source": [ "model.preprocess_name = None\n", "model.preprocess_dependencies = None" ] }, { "cell_type": "code", "execution_count": 11, "id": "feaa129d", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:34:31.703759Z", "iopub.status.busy": "2026-07-04T19:34:31.703629Z", "iopub.status.idle": "2026-07-04T19:34:31.705412Z", "shell.execute_reply": "2026-07-04T19:34:31.704995Z" } }, "outputs": [], "source": [ "model.postprocess_name = None\n", "model.postprocess_dependencies = None" ] }, { "cell_type": "markdown", "id": "df4c3b96", "metadata": {}, "source": [ "## Check all clock parameters" ] }, { "cell_type": "code", "execution_count": 12, "id": "70aee7b6", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:34:31.706999Z", "iopub.status.busy": "2026-07-04T19:34:31.706887Z", "iopub.status.idle": "2026-07-04T19:34:31.711163Z", "shell.execute_reply": "2026-07-04T19:34:31.710672Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "%==================================== Model Details ====================================%\n", "Model Attributes:\n", "\n", "training: True\n", "metadata: {'approved_by_author': '⌛',\n", " 'citation': 'Tong, Huige, et al. \"Cell-type-specific and '\n", " 'cell-type-independent DNA methylation clocks.\" Aging 16 (2024).',\n", " 'clock_name': 'ctsliver',\n", " 'data_type': 'methylation',\n", " 'doi': 'https://doi.org/10.18632/aging.206184',\n", " 'notes': None,\n", " 'research_only': None,\n", " 'species': 'Homo sapiens',\n", " 'version': None,\n", " 'year': 2024}\n", "reference_values: None\n", "preprocess_name: None\n", "preprocess_dependencies: None\n", "postprocess_name: None\n", "postprocess_dependencies: None\n", "features: ['cg00147307', 'cg04055835', 'cg07014827', 'cg08639762', 'cg09085216', 'cg10501210', 'cg11037818', 'cg11837471', 'cg19861048', 'cg22793142', 'cg27553626', 'cg01139016', 'cg03602360', 'cg03957108', 'cg11797365', 'cg12477533', 'cg23059946', 'cg26469895', 'cg00481951', 'cg01633093', 'cg17631451', 'cg20669012', 'cg24572745', 'cg02650266', 'cg15848147', 'cg27652893', 'cg04671476', 'cg16049690', 'cg01017235', 'cg16867657']... [Total elements: 90]\n", "base_model_features: None\n", "\n", "%==================================== Model Details ====================================%\n", "Model Structure:\n", "\n", "base_model: LinearModel(\n", " (linear): Linear(in_features=90, out_features=1, bias=True)\n", ")\n", "\n", "%==================================== Model Details ====================================%\n", "Model Parameters and Weights:\n", "\n", "base_model.linear.weight: [0.06677141785621643, -0.4691475033760071, 8.956233978271484, -7.425961494445801, -0.37923702597618103, -0.9674519896507263, -0.2163476198911667, -0.6666942834854126, -0.0633813887834549, -11.506742477416992, -4.447482585906982, -0.7794511914253235, 1.741921067237854, 3.4112987518310547, 1.951097846031189, 4.32723331451416, -7.400779724121094, -0.8474096059799194, 1.4585193395614624, -2.9431684017181396, -0.044251661747694016, -2.712244987487793, -3.016547918319702, 1.0454469919204712, 0.705701470375061, -5.014070510864258, 2.0638656616210938, 0.18794922530651093, 1.635787010192871, 51.198280334472656]... [Tensor of shape torch.Size([1, 90])]\n", "base_model.linear.bias: tensor([48.3286])\n", "\n", "%==================================== Model Details ====================================%\n", "\n" ] } ], "source": [ "pya.utils.print_model_details(model)" ] }, { "cell_type": "markdown", "id": "c9337e54", "metadata": {}, "source": [ "## Basic test" ] }, { "cell_type": "code", "execution_count": 13, "id": "9b312d09", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:34:31.712546Z", "iopub.status.busy": "2026-07-04T19:34:31.712464Z", "iopub.status.idle": "2026-07-04T19:34:31.716977Z", "shell.execute_reply": "2026-07-04T19:34:31.716629Z" } }, "outputs": [ { "data": { "text/plain": [ "tensor([[140.2069],\n", " [ 45.0042],\n", " [ -4.2454],\n", " [-15.0873],\n", " [-27.0882],\n", " [150.2301],\n", " [ 29.9997],\n", " [257.3345],\n", " [ 42.9376],\n", " [-70.8377]], 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": "83e57549", "metadata": {}, "source": [ "## Save torch model" ] }, { "cell_type": "code", "execution_count": 14, "id": "d6d691ba", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:34:31.718563Z", "iopub.status.busy": "2026-07-04T19:34:31.718473Z", "iopub.status.idle": "2026-07-04T19:34:31.722639Z", "shell.execute_reply": "2026-07-04T19:34:31.722107Z" } }, "outputs": [], "source": [ "torch.save(model, f\"../weights/{model.metadata['clock_name']}.pt\")" ] }, { "cell_type": "markdown", "id": "492ca0ea", "metadata": {}, "source": [ "## Clear directory\n", "" ] }, { "cell_type": "code", "execution_count": 15, "id": "34e2c2a5", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:34:31.724060Z", "iopub.status.busy": "2026-07-04T19:34:31.723971Z", "iopub.status.idle": "2026-07-04T19:34:31.727766Z", "shell.execute_reply": "2026-07-04T19:34:31.727381Z" } }, "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 }