{ "cells": [ { "cell_type": "markdown", "id": "2f04eee0-5928-4e74-a754-6dc2e528810c", "metadata": {}, "source": [ "# HypoClock" ] }, { "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", "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": "d95fafdc-643a-40ea-a689-200bd132e90c", "metadata": {}, "source": [ "Let's first import some packages:" ] }, { "cell_type": "code", "execution_count": 1, "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": 2, "id": "8aa77372-7ed3-4da7-abc9-d30372106139", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "class HypoClock(pyagingModel):\n", " def __init__(self):\n", " super().__init__()\n", "\n", " def preprocess(self, x):\n", " \"\"\"\n", " Compute mean beta per sample, excluding missing (-1) values.\n", " \"\"\"\n", " means = []\n", " for row in x:\n", " filtered_row = row[row != -1]\n", " if len(filtered_row) > 0:\n", " mean = torch.mean(filtered_row)\n", " else:\n", " mean = torch.tensor(float(\"nan\"), device=x.device, dtype=x.dtype)\n", " means.append(mean)\n", " return torch.vstack(means)\n", "\n", " def postprocess(self, x):\n", " return 1 - x\n", "\n" ] } ], "source": [ "def print_entire_class(cls):\n", " source = inspect.getsource(cls)\n", " print(source)\n", "\n", "print_entire_class(pya.models.HypoClock)" ] }, { "cell_type": "code", "execution_count": 3, "id": "78536494-f1d9-44de-8583-c89a310d2307", "metadata": {}, "outputs": [], "source": [ "model = pya.models.HypoClock()" ] }, { "cell_type": "markdown", "id": "51f8615e-01fa-4aa5-b196-3ee2b35d261c", "metadata": {}, "source": [ "## Define clock metadata" ] }, { "cell_type": "code", "execution_count": 4, "id": "6601da9e-8adc-44ee-9308-75e3cd31b816", "metadata": {}, "outputs": [], "source": [ "model.metadata[\"clock_name\"] = \"hypoclock\"\n", "model.metadata[\"data_type\"] = \"DNA methylation\" # Paper: HypoClock is based on DNA methylation at solo-WCGW sites.\n", "model.metadata[\"species\"] = \"Homo sapiens\" # Paper: The HypoClock analysis uses human Illumina 450K solo-WCGW probes.\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\"] = \"Pyaging returns an inverted HypoClock burden score, 1 minus the mean beta value across 678 solo-WCGW CpGs; higher values therefore indicate deeper PMD hypomethylation. The assigned 2018 paper is the biological precursor, while the named 678-site implementation is from 2020.\"\n", "model.metadata[\"research_only\"] = None\n", "model.metadata[\"tissue\"] = [\"multi-tissue\"] # Paper: Solo-WCGW PMD hypomethylation was evaluated across diverse normal tissues, blood lineages and primary tumors.\n", "model.metadata[\"predicts\"] = [\"mitotic age\"] # Paper: HypoClock is a mitotic-like model based on hypomethylation at solo-WCGW sites.\n", "model.metadata[\"training_target\"] = [\"not applicable\"] # Paper: HypoClock is calculated as an average methylation score rather than fit to an outcome.\n", "model.metadata[\"unit\"] = [\"beta value\"] # Paper: The packaged output is one minus mean methylation across the selected CpGs, retaining a methylation beta-derived scale.\n", "model.metadata[\"model_type\"] = \"mean aggregation\" # Paper: The score is the average DNAm over selected solo-WCGW probes.\n", "model.metadata[\"platform\"] = [\"Illumina 450K\"] # Paper: The 678-site implementation uses solo-WCGWs represented on Illumina 450K arrays.\n", "model.metadata[\"population\"] = \"human, age unspecified\" # Paper: HypoClock was assessed across normal adult tissues, premalignant lesions and cancers.\n", "model.metadata[\"journal\"] = \"Genome Medicine\"\n", "model.metadata[\"last_author\"] = \"Andrew E. Teschendorff\"\n", "model.metadata[\"n_features\"] = 678\n", "model.metadata[\"citations\"] = 452\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 directly with curl" ] }, { "cell_type": "code", "execution_count": 5, "id": "6b57cb84-b940-4cfe-8933-3955cab9dfe9", "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ " % Total % Received % Xferd Average Speed Time Time Time Current\n", " Dload Upload Total Spent Left Speed\n", "100 30851 100 30851 0 0 425k 0 --:--:-- --:--:-- --:--:-- 430k\n" ] }, { "data": { "text/plain": [ "0" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "supplementary_url = \"https://raw.githubusercontent.com/aet21/EpiMitClocks/master/data/dataETOC3.rda\"\n", "supplementary_file_name = \"dataETOC3.rda\"\n", "os.system(f\"curl -L -o {supplementary_file_name} {supplementary_url}\")" ] }, { "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 R data" ] }, { "cell_type": "code", "execution_count": 6, "id": "110a5ded-d25f-4cef-8e84-4f51210dfc26", "metadata": {}, "outputs": [], "source": [ "r_cmd = (\n", " \"load('dataETOC3.rda'); \"\n", " \"df <- data.frame(cpg=dataETOC3.l[[4]]); \"\n", " \"write.csv(df, 'hypoclock_cpgs.csv', row.names=FALSE)\"\n", ")\n", "os.system(f\"Rscript -e \\\"{r_cmd}\\\"\")\n", "\n", "features_df = pd.read_csv('hypoclock_cpgs.csv')\n", "model.features = features_df['cpg'].tolist()\n", "\n", "assert len(model.features) == 678, f\"Expected 678 CpGs, got {len(model.features)}\"" ] }, { "cell_type": "markdown", "id": "ee6d8fa0-4767-4c45-9717-eb1c95e2ddc0", "metadata": {}, "source": [ "## Load weights into base model" ] }, { "cell_type": "code", "execution_count": 8, "id": "e09b3463-4fd4-41b1-ac21-e63ddd223fe0", "metadata": {}, "outputs": [], "source": [ "weights = torch.tensor([1.0]).unsqueeze(0)\n", "intercept = torch.tensor([0.0])" ] }, { "cell_type": "markdown", "id": "ad261636-5b00-4979-bb1d-67a851f7aa19", "metadata": {}, "source": [ "#### Linear model" ] }, { "cell_type": "code", "execution_count": 9, "id": "d7f43b99-26f2-4622-9a76-316712058877", "metadata": {}, "outputs": [], "source": [ "base_model = pya.models.LinearModel(input_dim=1)\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": "ad8b4c1d-9d57-48b7-9a30-bcfea7b747b1", "metadata": {}, "source": [ "## Load reference values" ] }, { "cell_type": "code", "execution_count": 10, "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": [ "## Load preprocess and postprocess objects" ] }, { "cell_type": "code", "execution_count": 11, "id": "7a22fb20-c605-424d-8efb-7620c2c0755c", "metadata": {}, "outputs": [], "source": [ "model.preprocess_name = \"mean\"\n", "model.preprocess_dependencies = None" ] }, { "cell_type": "code", "execution_count": 12, "id": "ff4a21cb-cf41-44dc-9ed1-95cf8aa15772", "metadata": {}, "outputs": [], "source": [ "model.postprocess_name = \"one_minus\"\n", "model.postprocess_dependencies = None" ] }, { "cell_type": "markdown", "id": "86e3d6b1-e67e-4f3d-bd39-0ebec5726c3c", "metadata": {}, "source": [ "## Check all clock parameters" ] }, { "cell_type": "code", "execution_count": 13, "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': 'Zhou, Wanding, et al. \"DNA methylation loss in late-replicating '\n", " 'domains is linked to mitotic cell division.\" Nature Genetics 50, '\n", " 'no. 4 (2018): 591-602.',\n", " 'clock_name': 'hypoclock',\n", " 'data_type': 'methylation',\n", " 'doi': 'https://doi.org/10.1038/s41588-018-0073-4',\n", " 'notes': 'HypoClock score is 1 - mean beta across 678 solo-WCGW CpGs; '\n", " 'reference values are -1 to ignore missing.',\n", " 'research_only': None,\n", " 'species': 'Homo sapiens',\n", " 'version': None,\n", " 'year': 2018}\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: 678]\n", "preprocess_name: 'mean'\n", "preprocess_dependencies: None\n", "postprocess_name: 'one_minus'\n", "postprocess_dependencies: None\n", "features: ['cg01689796', 'cg17753162', 'cg26150621', 'cg11684734', 'cg05812697', 'cg24052817', 'cg01827202', 'cg12277524', 'cg06160606', 'cg12758960', 'cg12270633', 'cg25939869', 'cg16823292', 'cg17041296', 'cg17325792', 'cg05347985', 'cg04789392', 'cg16320208', 'cg01779525', 'cg08009265', 'cg08244156', 'cg14711592', 'cg16577588', 'cg03114253', 'cg02245566', 'cg22601108', 'cg01068621', 'cg21291134', 'cg20491963', 'cg07725889']... [Total elements: 678]\n", "base_model_features: None\n", "\n", "%==================================== Model Details ====================================%\n", "Model Structure:\n", "\n", "base_model: LinearModel(\n", " (linear): Linear(in_features=1, 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": "986d0262-e0c7-4036-b687-dee53ba392fb", "metadata": {}, "source": [ "## Basic test" ] }, { "cell_type": "code", "execution_count": 14, "id": "936b9877-d076-4ced-99aa-e8d4c58c5caf", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "tensor([[0.9638],\n", " [0.9622],\n", " [1.0423],\n", " [1.0675],\n", " [1.0330],\n", " [0.9733],\n", " [0.9686],\n", " [1.0028],\n", " [0.9955],\n", " [0.9212]], dtype=torch.float64, grad_fn=)" ] }, "execution_count": 14, "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": "fe8299d7-9285-4e22-82fd-b664434b4369", "metadata": {}, "source": [ "## Save torch model" ] }, { "cell_type": "code", "execution_count": 15, "id": "5ef2fa8d-c80b-4fdd-8555-79c0d541788e", "metadata": {}, "outputs": [], "source": [ "torch.save(model, f\"../weights/{model.metadata['clock_name']}.pt\")" ] }, { "cell_type": "markdown", "id": "bac6257b-8d08-4a90-8d0b-7f745dc11ac1", "metadata": {}, "source": [ "## Clear directory\n", "" ] }, { "cell_type": "code", "execution_count": 16, "id": "11aeaa70-44c0-42f9-86d7-740e3849a7a6", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Deleted file: dataETOC3.rda\n", "Deleted file: hypoclock_cpgs.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": ".venv", "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.7" } }, "nbformat": 4, "nbformat_minor": 5 }