{ "cells": [ { "cell_type": "markdown", "id": "b98d8bbd", "metadata": {}, "source": [ "# NeuSin" ] }, { "cell_type": "markdown", "id": "a25f3291", "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": "70ce8a24", "metadata": {}, "source": [ "Let's first import some packages:" ] }, { "cell_type": "code", "execution_count": 1, "id": "529eb4b3", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:34:16.318329Z", "iopub.status.busy": "2026-07-04T19:34:16.318218Z", "iopub.status.idle": "2026-07-04T19:34:18.210883Z", "shell.execute_reply": "2026-07-04T19:34:18.210278Z" } }, "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": "0e8071c3", "metadata": {}, "source": [ "## Instantiate model class" ] }, { "cell_type": "code", "execution_count": 2, "id": "7c101cb5", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:34:18.213081Z", "iopub.status.busy": "2026-07-04T19:34:18.212867Z", "iopub.status.idle": "2026-07-04T19:34:18.215882Z", "shell.execute_reply": "2026-07-04T19:34:18.215493Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "class NeuSin(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.NeuSin)" ] }, { "cell_type": "code", "execution_count": 3, "id": "99737934", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:34:18.217039Z", "iopub.status.busy": "2026-07-04T19:34:18.216960Z", "iopub.status.idle": "2026-07-04T19:34:18.218791Z", "shell.execute_reply": "2026-07-04T19:34:18.218367Z" } }, "outputs": [], "source": [ "model = pya.models.NeuSin()" ] }, { "cell_type": "markdown", "id": "7310894e", "metadata": {}, "source": [ "## Define clock metadata" ] }, { "cell_type": "code", "execution_count": 4, "id": "d9717346", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:34:18.219894Z", "iopub.status.busy": "2026-07-04T19:34:18.219818Z", "iopub.status.idle": "2026-07-04T19:34:18.221803Z", "shell.execute_reply": "2026-07-04T19:34:18.221327Z" } }, "outputs": [], "source": [ "model.metadata[\"clock_name\"] = \"neusin\"\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): 13452–13504.\"\n", "model.metadata[\"doi\"] = \"https://doi.org/10.18632/aging.206184\"\n", "model.metadata[\"notes\"] = \"Neu-Sin is a neuron semi-intrinsic chronological-age clock: elastic-net regression was restricted to neuron age-DMCTs but fitted to methylation values not adjusted for brain cell fractions.\"\n", "model.metadata[\"research_only\"] = None\n", "model.metadata[\"tissue\"] = [\"brain cortex\"] # Paper: For training the clocks, we used one of the largest collections of prefrontal cortex (PFC) samples profiled with Illumina 450k technology, encompassing 416 samples with a wide age range (18–97 years).\n", "model.metadata[\"predicts\"] = [\"chronological age\"] # Paper: Finally, elastic net predictors of chronological age are trained from the Neu-DMCTs parameterized by a penalty parameter.\n", "model.metadata[\"training_target\"] = [\"chronological age\"] # Paper: Having identified the significant neuron-DMCTs, we next trained Elastic Net regression (glmnet R package) models (alpha = 0.5) for age, each parameterized by a different penalty parameter (lambda) value.\n", "model.metadata[\"unit\"] = [\"years\"] # Paper: For training the clocks, we used one of the largest collections of prefrontal cortex (PFC) samples profiled with Illumina 450k technology, encompassing 416 samples with a wide age range (18–97 years).\n", "model.metadata[\"model_type\"] = \"elastic net regression\" # Paper: Having identified the significant neuron-DMCTs, we next trained Elastic Net regression (glmnet R package) models (alpha = 0.5) for age, each parameterized by a different penalty parameter (lambda) value.\n", "model.metadata[\"platform\"] = [\"Illumina 450K\"] # Paper: For training the clocks, we used one of the largest collections of prefrontal cortex (PFC) samples profiled with Illumina 450k technology, encompassing 416 samples with a wide age range (18–97 years).\n", "model.metadata[\"population\"] = \"adults\" # Paper: For training the clocks, we used one of the largest collections of prefrontal cortex (PFC) samples profiled with Illumina 450k technology, encompassing 416 samples with a wide age range (18–97 years).\n", "model.metadata[\"journal\"] = \"Aging\"\n", "model.metadata[\"last_author\"] = \"Andrew E. Teschendorff\"\n", "model.metadata[\"n_features\"] = 672 # Paper: The official Neu-SinCoef.rda object contains 673 rows: one (Intercept) row and 672 non-intercept CpG coefficient rows.\n", "model.metadata[\"citations\"] = 25\n", "model.metadata[\"citations_date\"] = \"2026-07-05\"\n" ] }, { "cell_type": "markdown", "id": "1a913a9f", "metadata": {}, "source": [ "## Download clock dependencies" ] }, { "cell_type": "code", "execution_count": 5, "id": "2c825a05", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:34:18.223013Z", "iopub.status.busy": "2026-07-04T19:34:18.222925Z", "iopub.status.idle": "2026-07-04T19:34:18.346718Z", "shell.execute_reply": "2026-07-04T19:34:18.346138Z" } }, "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/Neu-Sin.csv\"\n", "supplementary_file_name = \"coefficients.csv\"\n", "os.system(f\"curl -sL -o {supplementary_file_name} {supplementary_url}\")" ] }, { "cell_type": "markdown", "id": "9fe7e1a6", "metadata": {}, "source": [ "## Load features" ] }, { "cell_type": "code", "execution_count": 6, "id": "822b228a", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:34:18.348203Z", "iopub.status.busy": "2026-07-04T19:34:18.348088Z", "iopub.status.idle": "2026-07-04T19:34:18.353294Z", "shell.execute_reply": "2026-07-04T19:34:18.352777Z" } }, "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": "953e20a0", "metadata": {}, "source": [ "## Load weights into base model" ] }, { "cell_type": "code", "execution_count": 7, "id": "b1f43f8f", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:34:18.355010Z", "iopub.status.busy": "2026-07-04T19:34:18.354888Z", "iopub.status.idle": "2026-07-04T19:34:18.357299Z", "shell.execute_reply": "2026-07-04T19:34:18.356902Z" } }, "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": "e5a88e18", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:34:18.358564Z", "iopub.status.busy": "2026-07-04T19:34:18.358471Z", "iopub.status.idle": "2026-07-04T19:34:18.360706Z", "shell.execute_reply": "2026-07-04T19:34:18.360350Z" } }, "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": "9a6a19cc", "metadata": {}, "source": [ "## Load reference values" ] }, { "cell_type": "code", "execution_count": 9, "id": "1dd4cfbf", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:34:18.362083Z", "iopub.status.busy": "2026-07-04T19:34:18.361994Z", "iopub.status.idle": "2026-07-04T19:34:18.363689Z", "shell.execute_reply": "2026-07-04T19:34:18.363334Z" } }, "outputs": [], "source": [ "model.reference_values = None" ] }, { "cell_type": "markdown", "id": "719143bf", "metadata": {}, "source": [ "## Load preprocess and postprocess objects" ] }, { "cell_type": "code", "execution_count": 10, "id": "1332993b", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:34:18.364964Z", "iopub.status.busy": "2026-07-04T19:34:18.364887Z", "iopub.status.idle": "2026-07-04T19:34:18.366576Z", "shell.execute_reply": "2026-07-04T19:34:18.366299Z" } }, "outputs": [], "source": [ "model.preprocess_name = None\n", "model.preprocess_dependencies = None" ] }, { "cell_type": "code", "execution_count": 11, "id": "21e4c8ff", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:34:18.367778Z", "iopub.status.busy": "2026-07-04T19:34:18.367709Z", "iopub.status.idle": "2026-07-04T19:34:18.369415Z", "shell.execute_reply": "2026-07-04T19:34:18.369004Z" } }, "outputs": [], "source": [ "model.postprocess_name = None\n", "model.postprocess_dependencies = None" ] }, { "cell_type": "markdown", "id": "700bca59", "metadata": {}, "source": [ "## Check all clock parameters" ] }, { "cell_type": "code", "execution_count": 12, "id": "19935e87", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:34:18.370544Z", "iopub.status.busy": "2026-07-04T19:34:18.370476Z", "iopub.status.idle": "2026-07-04T19:34:18.373861Z", "shell.execute_reply": "2026-07-04T19:34:18.373460Z" } }, "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': 'neusin',\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: ['cg10626816', 'cg13571388', 'cg17826530', 'cg06711298', 'cg08193650', 'cg10442729', 'cg17343483', 'cg20361600', 'cg21185289', 'cg16369288', 'cg22702772', 'cg26856080', 'cg06385118', 'cg18171715', 'cg18586891', 'cg05477834', 'cg15690342', 'cg18635552', 'cg18745317', 'cg25108022', 'cg00537387', 'cg08692175', 'cg25739875', 'cg18048071', 'cg19421584', 'cg22493372', 'cg02324367', 'cg05492433', 'cg16241714', 'cg26003909']... [Total elements: 672]\n", "base_model_features: None\n", "\n", "%==================================== Model Details ====================================%\n", "Model Structure:\n", "\n", "base_model: LinearModel(\n", " (linear): Linear(in_features=672, out_features=1, bias=True)\n", ")\n", "\n", "%==================================== Model Details ====================================%\n", "Model Parameters and Weights:\n", "\n", "base_model.linear.weight: [0.6255767941474915, 0.00018867039761971682, 1.4650660753250122, -4.989912986755371, 2.8106305599212646, 3.3365237712860107, -8.365673065185547, -7.561515808105469, -2.2176127433776855, 2.238844394683838, 5.353684425354004, 18.882240295410156, -1.537793755531311, 18.469179153442383, 0.3016071319580078, -0.4679134786128998, 0.7296689748764038, -9.179381370544434, 0.04645940288901329, 7.833886623382568, -2.897672414779663, -21.346012115478516, 9.050196647644043, 0.5711203813552856, 0.47357064485549927, 0.11948469281196594, 0.0023688615765422583, -1.3019375801086426, 57.94570541381836, -2.4218344688415527]... [Tensor of shape torch.Size([1, 672])]\n", "base_model.linear.bias: tensor([20.1315])\n", "\n", "%==================================== Model Details ====================================%\n", "\n" ] } ], "source": [ "pya.utils.print_model_details(model)" ] }, { "cell_type": "markdown", "id": "374f688c", "metadata": {}, "source": [ "## Basic test" ] }, { "cell_type": "code", "execution_count": 13, "id": "27adbf83", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:34:18.375233Z", "iopub.status.busy": "2026-07-04T19:34:18.375157Z", "iopub.status.idle": "2026-07-04T19:34:18.379712Z", "shell.execute_reply": "2026-07-04T19:34:18.379310Z" } }, "outputs": [ { "data": { "text/plain": [ "tensor([[ -26.3359],\n", " [ 213.3675],\n", " [-104.1039],\n", " [-339.0749],\n", " [ -66.5274],\n", " [ 113.9317],\n", " [ 141.6260],\n", " [ -65.5180],\n", " [ -2.5413],\n", " [-400.5478]], 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": "0504f077", "metadata": {}, "source": [ "## Save torch model" ] }, { "cell_type": "code", "execution_count": 14, "id": "a0310962", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:34:18.380936Z", "iopub.status.busy": "2026-07-04T19:34:18.380858Z", "iopub.status.idle": "2026-07-04T19:34:18.384506Z", "shell.execute_reply": "2026-07-04T19:34:18.384114Z" } }, "outputs": [], "source": [ "torch.save(model, f\"../weights/{model.metadata['clock_name']}.pt\")" ] }, { "cell_type": "markdown", "id": "acbaca64", "metadata": {}, "source": [ "## Clear directory\n", "" ] }, { "cell_type": "code", "execution_count": 15, "id": "f435c343", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T19:34:18.385614Z", "iopub.status.busy": "2026-07-04T19:34:18.385544Z", "iopub.status.idle": "2026-07-04T19:34:18.389006Z", "shell.execute_reply": "2026-07-04T19:34:18.388548Z" } }, "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 }