{ "cells": [ { "cell_type": "markdown", "id": "75120104", "metadata": {}, "source": [ "# HepatoXu" ] }, { "cell_type": "markdown", "id": "9423ade4", "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": "27f44369", "metadata": {}, "source": [ "Let's first import some packages:" ] }, { "cell_type": "code", "execution_count": 1, "id": "d5eb6946", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T20:01:06.847167Z", "iopub.status.busy": "2026-07-04T20:01:06.846870Z", "iopub.status.idle": "2026-07-04T20:01:09.018804Z", "shell.execute_reply": "2026-07-04T20:01:09.018315Z" } }, "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": "a4323330", "metadata": {}, "source": [ "## Instantiate model class" ] }, { "cell_type": "code", "execution_count": 2, "id": "b856a836", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T20:01:09.020556Z", "iopub.status.busy": "2026-07-04T20:01:09.020342Z", "iopub.status.idle": "2026-07-04T20:01:09.023367Z", "shell.execute_reply": "2026-07-04T20:01:09.022973Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "class HepatoXu(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.HepatoXu)" ] }, { "cell_type": "code", "execution_count": 3, "id": "b59c8043", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T20:01:09.024760Z", "iopub.status.busy": "2026-07-04T20:01:09.024670Z", "iopub.status.idle": "2026-07-04T20:01:09.026371Z", "shell.execute_reply": "2026-07-04T20:01:09.026039Z" } }, "outputs": [], "source": [ "model = pya.models.HepatoXu()" ] }, { "cell_type": "markdown", "id": "c74f8138", "metadata": {}, "source": [ "## Define clock metadata" ] }, { "cell_type": "code", "execution_count": 4, "id": "06084b28", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T20:01:09.027947Z", "iopub.status.busy": "2026-07-04T20:01:09.027775Z", "iopub.status.idle": "2026-07-04T20:01:09.029957Z", "shell.execute_reply": "2026-07-04T20:01:09.029544Z" } }, "outputs": [], "source": [ "model.metadata[\"clock_name\"] = \"hepatoxu\"\n", "model.metadata[\"data_type\"] = \"DNA methylation\" # Paper: The study developed circulating tumour-DNA methylation markers.\n", "model.metadata[\"species\"] = \"Homo sapiens\" # Paper: Plasma samples came from human HCC patients and normal controls.\n", "model.metadata[\"year\"] = 2017\n", "model.metadata[\"approved_by_author\"] = \"⌛\"\n", "model.metadata[\"citation\"] = \"Xu, R.-H., et al. “Circulating tumour DNA methylation markers for diagnosis and prognosis of hepatocellular carcinoma.” Nature Materials 16: 1155–1161 (2017).\"\n", "model.metadata[\"doi\"] = \"https://doi.org/10.1038/nmat4997\"\n", "model.metadata[\"notes\"] = \"Ten-marker plasma cfDNA methylation logistic model producing the combined HCC diagnosis score (cd-score); this packaged model does not implement the separate eight-marker prognosis score.\"\n", "model.metadata[\"research_only\"] = None\n", "model.metadata[\"tissue\"] = [\"plasma cell-free DNA\"] # Paper: The diagnostic dataset comprised plasma cfDNA from HCC patients and normal controls.\n", "model.metadata[\"predicts\"] = [\"hepatocellular carcinoma\"] # Paper: The ten-marker model produced a combined diagnosis score designated cd-score.\n", "model.metadata[\"training_target\"] = [\"hepatocellular carcinoma\"] # Paper: The logistic regression was fitted as a binary prediction of HCC versus normal plasma samples.\n", "model.metadata[\"unit\"] = [\"unitless\"] # Paper: The packaged LinearReferenceClock returns the weighted linear score without a sigmoid transformation.\n", "model.metadata[\"model_type\"] = \"feature-selected logistic regression\" # Paper: Ten overlapping markers from LASSO and random forest were used as covariates in logistic regression.\n", "model.metadata[\"platform\"] = [\"targeted bisulfite sequencing\"] # Paper: Chinese plasma methylation values were obtained by targeted bisulfite sequencing using molecular inversion probes.\n", "model.metadata[\"population\"] = \"adults\" # Paper: The 1,933-sample dataset was split 2:1; the training set had 1,275 samples from 715 HCC and 560 normal samples.\n", "model.metadata[\"journal\"] = \"Nature Materials\"\n", "model.metadata[\"last_author\"] = \"Kang Zhang\"\n", "model.metadata[\"n_features\"] = 10\n", "model.metadata[\"citations\"] = 884\n", "model.metadata[\"citations_date\"] = \"2026-07-05\"\n" ] }, { "cell_type": "markdown", "id": "84f7d40b", "metadata": {}, "source": [ "## Download clock dependencies" ] }, { "cell_type": "code", "execution_count": 5, "id": "2caf0f4e", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T20:01:09.031390Z", "iopub.status.busy": "2026-07-04T20:01:09.031300Z", "iopub.status.idle": "2026-07-04T20:01:09.326457Z", "shell.execute_reply": "2026-07-04T20:01:09.324898Z" } }, "outputs": [ { "data": { "text/plain": [ "0" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "os.system(f\"curl -sL -o coefficients.csv https://raw.githubusercontent.com/bio-learn/biolearn/180852e2bab473303cb85da627178b1695ee9d86/biolearn/data/HepatoXu.csv\")" ] }, { "cell_type": "markdown", "id": "7201a362", "metadata": {}, "source": [ "## Load features" ] }, { "cell_type": "code", "execution_count": 6, "id": "db59d912", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T20:01:09.329567Z", "iopub.status.busy": "2026-07-04T20:01:09.329308Z", "iopub.status.idle": "2026-07-04T20:01:09.335291Z", "shell.execute_reply": "2026-07-04T20:01:09.334753Z" } }, "outputs": [], "source": [ "df = pd.read_csv('coefficients.csv')\n", "mask = df['CpGmarker'].astype(str).str.lower().isin(['intercept', '(intercept)'])\n", "intercept_value = float(df.loc[mask, 'CoefficientTraining'].iloc[0]) if mask.any() else 0.0\n", "coef_df = df.loc[~mask].reset_index(drop=True)\n", "model.features = coef_df['CpGmarker'].tolist()" ] }, { "cell_type": "markdown", "id": "8bd3ed80", "metadata": {}, "source": [ "## Load weights into base model" ] }, { "cell_type": "code", "execution_count": 7, "id": "cea12cd0", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T20:01:09.337020Z", "iopub.status.busy": "2026-07-04T20:01:09.336909Z", "iopub.status.idle": "2026-07-04T20:01:09.339348Z", "shell.execute_reply": "2026-07-04T20:01:09.338919Z" } }, "outputs": [], "source": [ "weights = torch.tensor(coef_df['CoefficientTraining'].tolist()).unsqueeze(0).float()\n", "intercept = torch.tensor([intercept_value]).float()" ] }, { "cell_type": "code", "execution_count": 8, "id": "6dc7b67c", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T20:01:09.340661Z", "iopub.status.busy": "2026-07-04T20:01:09.340558Z", "iopub.status.idle": "2026-07-04T20:01:09.343969Z", "shell.execute_reply": "2026-07-04T20:01:09.343023Z" } }, "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": "ff84857e", "metadata": {}, "source": [ "## Load reference values" ] }, { "cell_type": "code", "execution_count": 9, "id": "6ba5764a", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T20:01:09.346856Z", "iopub.status.busy": "2026-07-04T20:01:09.346595Z", "iopub.status.idle": "2026-07-04T20:01:09.349300Z", "shell.execute_reply": "2026-07-04T20:01:09.348309Z" } }, "outputs": [], "source": [ "model.reference_values = None" ] }, { "cell_type": "markdown", "id": "2873ddaa", "metadata": {}, "source": [ "## Load preprocess and postprocess objects" ] }, { "cell_type": "code", "execution_count": 10, "id": "9531ad3b", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T20:01:09.351357Z", "iopub.status.busy": "2026-07-04T20:01:09.351016Z", "iopub.status.idle": "2026-07-04T20:01:09.353613Z", "shell.execute_reply": "2026-07-04T20:01:09.353154Z" } }, "outputs": [], "source": [ "model.preprocess_name = None\n", "model.preprocess_dependencies = None" ] }, { "cell_type": "code", "execution_count": 11, "id": "66e4dd16", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T20:01:09.355183Z", "iopub.status.busy": "2026-07-04T20:01:09.355063Z", "iopub.status.idle": "2026-07-04T20:01:09.357162Z", "shell.execute_reply": "2026-07-04T20:01:09.356738Z" } }, "outputs": [], "source": [ "model.postprocess_name = None\n", "model.postprocess_dependencies = None" ] }, { "cell_type": "markdown", "id": "c7b957c4", "metadata": {}, "source": [ "## Check all clock parameters" ] }, { "cell_type": "code", "execution_count": 12, "id": "5cb0746c", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T20:01:09.358629Z", "iopub.status.busy": "2026-07-04T20:01:09.358518Z", "iopub.status.idle": "2026-07-04T20:01:09.361896Z", "shell.execute_reply": "2026-07-04T20:01:09.361525Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "%==================================== Model Details ====================================%\n", "Model Attributes:\n", "\n", "training: True\n", "metadata: {'approved_by_author': '⌛',\n", " 'citation': 'Xu, Ruo-Han, et al. \"Circulating tumour DNA methylation markers '\n", " 'for diagnosis and prognosis of hepatocellular carcinoma.\" Nature '\n", " 'Materials 16.11 (2017): 1155-1161.',\n", " 'clock_name': 'hepatoxu',\n", " 'data_type': 'methylation',\n", " 'doi': 'https://doi.org/10.1038/nmat4997',\n", " 'notes': None,\n", " 'research_only': None,\n", " 'species': 'Homo sapiens',\n", " 'version': None,\n", " 'year': 2017}\n", "reference_values: None\n", "preprocess_name: None\n", "preprocess_dependencies: None\n", "postprocess_name: None\n", "postprocess_dependencies: None\n", "features: ['cg10428836',\n", " 'cg26668608',\n", " 'cg25754195',\n", " 'cg05205842',\n", " 'cg11606215',\n", " 'cg24067911',\n", " 'cg18196829',\n", " 'cg23211949',\n", " 'cg17213048',\n", " 'cg25459300']\n", "base_model_features: None\n", "\n", "%==================================== Model Details ====================================%\n", "Model Structure:\n", "\n", "base_model: LinearModel(\n", " (linear): Linear(in_features=10, out_features=1, bias=True)\n", ")\n", "\n", "%==================================== Model Details ====================================%\n", "Model Parameters and Weights:\n", "\n", "base_model.linear.weight: tensor([[11.5430, 4.5570, 2.5190, -3.6120, 6.8650, -5.4390, -9.0780, -5.2090,\n", " 6.6600, 1.9940]])\n", "base_model.linear.bias: tensor([15.5950])\n", "\n", "%==================================== Model Details ====================================%\n", "\n" ] } ], "source": [ "pya.utils.print_model_details(model)" ] }, { "cell_type": "markdown", "id": "6082f471", "metadata": {}, "source": [ "## Basic test" ] }, { "cell_type": "code", "execution_count": 13, "id": "196acf66", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T20:01:09.363133Z", "iopub.status.busy": "2026-07-04T20:01:09.363062Z", "iopub.status.idle": "2026-07-04T20:01:09.367344Z", "shell.execute_reply": "2026-07-04T20:01:09.366970Z" } }, "outputs": [ { "data": { "text/plain": [ "tensor([[49.1148],\n", " [40.0752],\n", " [23.5150],\n", " [ 1.2405],\n", " [ 2.2419],\n", " [-6.4443],\n", " [ 1.1513],\n", " [33.1075],\n", " [61.1116],\n", " [22.9915]], 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": "7026f16d", "metadata": {}, "source": [ "## Save torch model" ] }, { "cell_type": "code", "execution_count": 14, "id": "3cca4d29", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T20:01:09.369544Z", "iopub.status.busy": "2026-07-04T20:01:09.369413Z", "iopub.status.idle": "2026-07-04T20:01:09.373084Z", "shell.execute_reply": "2026-07-04T20:01:09.372451Z" } }, "outputs": [], "source": [ "torch.save(model, f\"../weights/{model.metadata['clock_name']}.pt\")" ] }, { "cell_type": "markdown", "id": "618d9a6f", "metadata": {}, "source": [ "## Clear directory\n", "" ] }, { "cell_type": "code", "execution_count": 15, "id": "a1281a8d", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T20:01:09.374470Z", "iopub.status.busy": "2026-07-04T20:01:09.374369Z", "iopub.status.idle": "2026-07-04T20:01:09.381861Z", "shell.execute_reply": "2026-07-04T20:01:09.377484Z" } }, "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 }