{ "cells": [ { "cell_type": "markdown", "id": "2f04eee0-5928-4e74-a754-6dc2e528810c", "metadata": {}, "source": [ "# epiTOC2" ] }, { "cell_type": "markdown", "id": "a3f514a3-772c-4a14-afdf-5a8376851ff4", "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", "10. [Basic test](#Basic-test)\n", "11. [Save torch model](#Save-torch-model)\n", "12. [Clear directory](#Clear-directory)\n" ] }, { "cell_type": "markdown", "id": "d95fafdc-643a-40ea-a689-200bd132e90c", "metadata": {}, "source": [ "Let's first import some packages:" ] }, { "cell_type": "code", "execution_count": 30, "id": "4adfb4de-cd79-4913-a1af-9e23e9e236c9", "metadata": {}, "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": "145082e5-ced4-47ae-88c0-cb69773e3c5a", "metadata": {}, "source": [ "## Instantiate model class" ] }, { "cell_type": "code", "execution_count": 31, "id": "8aa77372-7ed3-4da7-abc9-d30372106139", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "class epiTOC2(pyagingModel):\n", " def __init__(self):\n", " super().__init__()\n", " self.delta = None\n", " self.beta0 = None\n", "\n", " def preprocess(self, x):\n", " \"\"\"\n", " Replace NaNs with zero; missing features should already be imputed via reference_values.\n", " \"\"\"\n", " return torch.nan_to_num(x, nan=0.0)\n", "\n", " def forward(self, x):\n", " x = self.preprocess(x)\n", "\n", " device = x.device\n", " dtype = x.dtype\n", "\n", " delta = self.delta.to(device=device, dtype=dtype)\n", " beta0 = self.beta0.to(device=device, dtype=dtype)\n", "\n", " denom = delta * (1 - beta0)\n", " denom = torch.where(denom == 0, torch.ones_like(denom), denom)\n", "\n", " contrib = (x - beta0) / denom\n", " k = contrib.size(1)\n", " vals = 2.0 * torch.sum(contrib, dim=1) / k\n", "\n", " return self.postprocess(vals.unsqueeze(1))\n", "\n", " def postprocess(self, x):\n", " return x\n", "\n" ] } ], "source": [ "def print_entire_class(cls):\n", " source = inspect.getsource(cls)\n", " print(source)\n", "\n", "print_entire_class(pya.models.epiTOC2)\n" ] }, { "cell_type": "code", "execution_count": 32, "id": "78536494-f1d9-44de-8583-c89a310d2307", "metadata": {}, "outputs": [], "source": [ "model = pya.models.epiTOC2()" ] }, { "cell_type": "markdown", "id": "51f8615e-01fa-4aa5-b196-3ee2b35d261c", "metadata": {}, "source": [ "## Define clock metadata" ] }, { "cell_type": "code", "execution_count": 33, "id": "6601da9e-8adc-44ee-9308-75e3cd31b816", "metadata": {}, "outputs": [], "source": [ "model.metadata[\"clock_name\"] = \"epitoc2\"\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\"] = 2020\n", "model.metadata[\"approved_by_author\"] = \"⌛\"\n", "model.metadata[\"citation\"] = \"Teschendorff, Andrew E. \\\"A comparison of epigenetic mitotic-like clocks for cancer risk prediction.\\\" Genome Medicine 12 (2020): 56.\"\n", "model.metadata[\"doi\"] = \"https://doi.org/10.1186/s13073-020-00752-3\"\n", "model.metadata[\"notes\"] = \"Dynamic methylation-transmission model returning total cumulative stem-cell divisions per stem cell; an intrinsic rate additionally requires chronological age but is not this implementation's returned value.\"\n", "model.metadata[\"research_only\"] = None\n", "model.metadata[\"tissue\"] = [\"whole blood\"] # Paper: Parameters were fitted in the Hannum whole-blood cohort.\n", "model.metadata[\"predicts\"] = [\"mitotic age\"] # Paper: The epiTOC2 estimate is total stem-cell divisions per stem cell.\n", "model.metadata[\"training_target\"] = [\"chronological age\"] # Paper: CpG dynamic-model parameters were fitted against age-associated methylation trajectories.\n", "model.metadata[\"unit\"] = [\"cell divisions per stem cell\"] # Paper: The model output is total stem-cell divisions per stem cell.\n", "model.metadata[\"model_type\"] = \"dynamic methylation transmission model\" # Paper: A dynamic model of methylation transmission with stem-cell divisions defines epiTOC2.\n", "model.metadata[\"platform\"] = [\"Illumina 450K\"] # Paper: The Hannum training cohort was measured on the Illumina 450K array.\n", "model.metadata[\"population\"] = \"adults\" # Paper: Model fitting used Hannum whole blood spanning ages 19 to 101.\n", "model.metadata[\"journal\"] = \"Genome Medicine\"\n", "model.metadata[\"last_author\"] = \"Andrew E. Teschendorff\"\n", "model.metadata[\"n_features\"] = 163\n", "model.metadata[\"citations\"] = 155\n", "model.metadata[\"citations_date\"] = \"2026-07-05\"\n" ] }, { "cell_type": "markdown", "id": "74492239-5aae-4026-9d90-6bc9c574c110", "metadata": {}, "source": [ "## Download clock dependencies" ] }, { "cell_type": "markdown", "id": "c07158bc-19c9-47de-8276-5d1dc5361b22", "metadata": {}, "source": [ "#### Download coefficient file" ] }, { "cell_type": "code", "execution_count": 34, "id": "6b57cb84-b940-4cfe-8933-3955cab9dfe9", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0" ] }, "execution_count": 34, "metadata": {}, "output_type": "execute_result" } ], "source": [ "coeff_url = \"https://raw.githubusercontent.com/bio-learn/biolearn/master/biolearn/data/EpiTOC2.csv\"\n", "os.system(f\"curl -L {coeff_url} -o EpiTOC2.csv\")\n" ] }, { "cell_type": "markdown", "id": "5035b180-3d1b-4432-8ebe-b9c92bd93a7f", "metadata": {}, "source": [ "## Load features" ] }, { "cell_type": "markdown", "id": "793d7b24-b1ef-4dd2-ac26-079f7b67fba7", "metadata": {}, "source": [ "#### From Excel file" ] }, { "cell_type": "code", "execution_count": 35, "id": "110a5ded-d25f-4cef-8e84-4f51210dfc26", "metadata": {}, "outputs": [], "source": [ "df = pd.read_csv('EpiTOC2.csv', index_col=0)\n", "df['feature'] = df.index.astype(str)\n", "model.features = df['feature'].tolist()\n" ] }, { "cell_type": "markdown", "id": "ee6d8fa0-4767-4c45-9717-eb1c95e2ddc0", "metadata": {}, "source": [ "## Load weights into base model\n" ] }, { "cell_type": "code", "execution_count": 36, "id": "e09b3463-4fd4-41b1-ac21-e63ddd223fe0", "metadata": {}, "outputs": [], "source": [ "#### From CSV file\n" ] }, { "cell_type": "code", "execution_count": 37, "id": "ad261636-5b00-4979-bb1d-67a851f7aa19", "metadata": {}, "outputs": [], "source": [ "model.delta = torch.tensor(df['delta'].values, dtype=torch.float32).unsqueeze(0)\n", "model.beta0 = torch.tensor(df['beta0'].values, dtype=torch.float32).unsqueeze(0)\n", "model.base_model = None\n" ] }, { "cell_type": "code", "execution_count": 38, "id": "d7f43b99-26f2-4622-9a76-316712058877", "metadata": {}, "outputs": [], "source": [ "#### Linear model\n" ] }, { "cell_type": "markdown", "id": "ad8b4c1d-9d57-48b7-9a30-bcfea7b747b1", "metadata": {}, "source": [ "# Not used; computation happens in the model forward\n" ] }, { "cell_type": "code", "execution_count": 39, "id": "ade0f4c9-2298-4fc3-bb72-d200907dd731", "metadata": {}, "outputs": [], "source": [ "model.reference_values = [-1]*len(model.features)" ] }, { "cell_type": "markdown", "id": "af3bcf7b-74a8-4d21-9ccb-4de0c2b0516b", "metadata": {}, "source": [ "model.reference_values = [0.0] * len(model.features)" ] }, { "cell_type": "code", "execution_count": 40, "id": "7a22fb20-c605-424d-8efb-7620c2c0755c", "metadata": {}, "outputs": [], "source": [ "model.preprocess_name = \"mean\"\n", "model.preprocess_dependencies = None" ] }, { "cell_type": "code", "execution_count": 41, "id": "ff4a21cb-cf41-44dc-9ed1-95cf8aa15772", "metadata": {}, "outputs": [], "source": [ "model.preprocess_name = \"nan_to_zero\"\n", "model.preprocess_dependencies = None\n" ] }, { "cell_type": "markdown", "id": "86e3d6b1-e67e-4f3d-bd39-0ebec5726c3c", "metadata": {}, "source": [ "model.postprocess_name = None\n", "model.postprocess_dependencies = None\n" ] }, { "cell_type": "code", "execution_count": 42, "id": "2168355c-47d9-475d-b816-49f65e74887c", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "%==================================== Model Details ====================================%\n", "Model Attributes:\n", "\n", "training: True\n", "metadata: {'approved_by_author': '⌛',\n", " 'citation': 'Teschendorff, Andrew E. \"A comparison of epigenetic mitotic-like '\n", " 'clocks for cancer risk prediction.\" Genome Medicine 12.1 (2020): '\n", " '56.',\n", " 'clock_name': 'epitoc2',\n", " 'data_type': 'methylation',\n", " 'doi': 'https://doi.org/10.1186/s13073-020-00752-3',\n", " 'notes': 'Stem cell division rate estimate using EpiTOC2.',\n", " 'research_only': None,\n", " 'species': 'Homo sapiens',\n", " 'version': None,\n", " 'year': 2020}\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: 163]\n", "preprocess_name: 'nan_to_zero'\n", "preprocess_dependencies: None\n", "postprocess_name: None\n", "postprocess_dependencies: None\n", "features: ['cg00043095', 'cg00347369', 'cg00397986', 'cg00466268', 'cg00884606', 'cg00916884', 'cg01435574', 'cg01537995', 'cg01587896', 'cg01699217', 'cg01783070', 'cg01830294', 'cg02150988', 'cg02186542', 'cg02266732', 'cg02631468', 'cg02726121', 'cg02796545', 'cg02964724', 'cg03045635', 'cg03111498', 'cg03140968', 'cg03181582', 'cg03430846', 'cg03450948', 'cg03603951', 'cg03874199', 'cg04188273', 'cg04408488', 'cg04431946']... [Total elements: 163]\n", "base_model_features: None\n", "base_model: None\n", "delta: [4.999999873689376e-05, 4.999999873689376e-05, 4.999999873689376e-05, 9.999999747378752e-05, 9.999999747378752e-05, 4.999999873689376e-05, 4.999999873689376e-05, 4.999999873689376e-05, 9.999999747378752e-05, 4.999999873689376e-05, 4.999999873689376e-05, 0.0002500000118743628, 9.999999747378752e-05, 4.999999873689376e-05, 4.999999873689376e-05, 4.999999873689376e-05, 4.999999873689376e-05, 9.999999747378752e-05, 4.999999873689376e-05, 0.0002500000118743628, 9.999999747378752e-05, 4.999999873689376e-05, 4.999999873689376e-05, 4.999999873689376e-05, 9.999999747378752e-05, 4.999999873689376e-05, 4.999999873689376e-05, 9.999999747378752e-06, 4.999999873689376e-05, 4.999999873689376e-05]... [Tensor of shape torch.Size([1, 163])]\n", "beta0: [0.019999999552965164, 0.05000000074505806, 0.05000000074505806, 0.05000000074505806, 0.009999999776482582, 0.05000000074505806, 0.05000000074505806, 0.05000000074505806, 0.029999999329447746, 0.05000000074505806, 0.03999999910593033, 0.0, 0.029999999329447746, 0.05000000074505806, 0.019999999552965164, 0.05000000074505806, 0.029999999329447746, 0.019999999552965164, 0.05000000074505806, 0.029999999329447746, 0.029999999329447746, 0.03999999910593033, 0.05000000074505806, 0.05000000074505806, 0.029999999329447746, 0.009999999776482582, 0.029999999329447746, 0.019999999552965164, 0.019999999552965164, 0.03999999910593033]... [Tensor of shape torch.Size([1, 163])]\n", "\n", "%==================================== Model Details ====================================%\n", "Model Structure:\n", "\n", "\n", "%==================================== Model Details ====================================%\n", "Model Parameters and Weights:\n", "\n", "\n", "%==================================== Model Details ====================================%\n", "\n" ] } ], "source": [ "pya.utils.print_model_details(model)" ] }, { "cell_type": "markdown", "id": "986d0262-e0c7-4036-b687-dee53ba392fb", "metadata": {}, "source": [ "## Basic test" ] }, { "cell_type": "code", "execution_count": 43, "id": "936b9877-d076-4ced-99aa-e8d4c58c5caf", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "tensor([[ 1562.6673],\n", " [-3824.6137],\n", " [ 645.1144],\n", " [-1810.9748],\n", " [ -142.2699],\n", " [ 1630.9714],\n", " [ 9229.4758],\n", " [ 4666.7934],\n", " [ 5489.9210],\n", " [ 1256.8648]], dtype=torch.float64)" ] }, "execution_count": 43, "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\n" ] }, { "cell_type": "markdown", "id": "fe8299d7-9285-4e22-82fd-b664434b4369", "metadata": {}, "source": [ "## Save torch model" ] }, { "cell_type": "code", "execution_count": 44, "id": "5bb2b45d", "metadata": {}, "outputs": [], "source": [ "torch.save(model, f\"../weights/{model.metadata['clock_name']}.pt\")" ] }, { "cell_type": "markdown", "id": "d3e22298", "metadata": {}, "source": [ "## Clear directory" ] }, { "cell_type": "code", "execution_count": 45, "id": "11aeaa70-44c0-42f9-86d7-740e3849a7a6", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Deleted file: EpiTOC2.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": "research", "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.9.7" } }, "nbformat": 4, "nbformat_minor": 5 }