{ "cells": [ { "cell_type": "markdown", "id": "46d559da", "metadata": {}, "source": [ "# ProstateCancerKirby" ] }, { "cell_type": "markdown", "id": "8aa57c2e", "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": "d3308068", "metadata": {}, "source": [ "Let's first import some packages:" ] }, { "cell_type": "code", "execution_count": 1, "id": "09724621", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T20:01:02.011903Z", "iopub.status.busy": "2026-07-04T20:01:02.011805Z", "iopub.status.idle": "2026-07-04T20:01:04.436127Z", "shell.execute_reply": "2026-07-04T20:01:04.435660Z" } }, "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": "82e72927", "metadata": {}, "source": [ "## Instantiate model class" ] }, { "cell_type": "code", "execution_count": 2, "id": "6eb80685", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T20:01:04.437965Z", "iopub.status.busy": "2026-07-04T20:01:04.437749Z", "iopub.status.idle": "2026-07-04T20:01:04.440859Z", "shell.execute_reply": "2026-07-04T20:01:04.440486Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "class ProstateCancerKirby(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.ProstateCancerKirby)" ] }, { "cell_type": "code", "execution_count": 3, "id": "b3729166", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T20:01:04.442075Z", "iopub.status.busy": "2026-07-04T20:01:04.441997Z", "iopub.status.idle": "2026-07-04T20:01:04.443726Z", "shell.execute_reply": "2026-07-04T20:01:04.443361Z" } }, "outputs": [], "source": [ "model = pya.models.ProstateCancerKirby()" ] }, { "cell_type": "markdown", "id": "c7ee5a04", "metadata": {}, "source": [ "## Define clock metadata" ] }, { "cell_type": "code", "execution_count": 4, "id": "10191303", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T20:01:04.445001Z", "iopub.status.busy": "2026-07-04T20:01:04.444905Z", "iopub.status.idle": "2026-07-04T20:01:04.447074Z", "shell.execute_reply": "2026-07-04T20:01:04.446613Z" } }, "outputs": [], "source": [ "model.metadata[\"clock_name\"] = \"prostatecancerkirby\"\n", "model.metadata[\"data_type\"] = \"DNA methylation\" # Paper: The classifier uses methylation beta values at three CpGs.\n", "model.metadata[\"species\"] = \"Homo sapiens\" # Paper: Prostate tissues were collected from human patients undergoing radical prostatectomy.\n", "model.metadata[\"year\"] = 2017\n", "model.metadata[\"approved_by_author\"] = \"⌛\"\n", "model.metadata[\"citation\"] = \"Kirby, M. K., et al. “Genome-wide DNA methylation measurements in prostate tissues uncovers novel prostate cancer diagnostic biomarkers and transcription factor binding patterns.” BMC Cancer 17: 273 (2017).\"\n", "model.metadata[\"doi\"] = \"https://doi.org/10.1186/s12885-017-3252-2\"\n", "model.metadata[\"notes\"] = \"Three-CpG prostate-tissue diagnostic classifier distinguishing malignant from benign-adjacent tissue; it was trained on 73 tumors and 63 benign-adjacent samples and externally validated in TCGA.\"\n", "model.metadata[\"research_only\"] = None\n", "model.metadata[\"tissue\"] = [\"prostate\"] # Paper: Fresh-frozen prostate cancers and benign-adjacent prostate tissues were profiled.\n", "model.metadata[\"predicts\"] = [\"prostate cancer\"] # Paper: The score distinguishes malignant prostate tissue from benign-adjacent tissue.\n", "model.metadata[\"training_target\"] = [\"prostate cancer\"] # Paper: Binomial logistic regression was fit to tumor versus benign-adjacent tissue status.\n", "model.metadata[\"unit\"] = [\"log odds\"] # Paper: The published classifier is the untransformed binomial-GLM linear predictor 6.52 − 17.04β1 + 24.18β2 − 13.82β3.\n", "model.metadata[\"model_type\"] = \"logistic regression\" # Paper: Logistic regression used glm with family=binomial.\n", "model.metadata[\"platform\"] = [\"Illumina 450K\"] # Paper: Training tissues were measured with the Illumina HumanMethylation450 BeadChip.\n", "model.metadata[\"population\"] = \"adult men\" # Paper: The training cohort had ages 43–73 years and supplied tumor/benign-adjacent prostate tissues.\n", "model.metadata[\"journal\"] = \"BMC Cancer\"\n", "model.metadata[\"last_author\"] = \"Richard M. Myers\"\n", "model.metadata[\"n_features\"] = 3\n", "model.metadata[\"citations\"] = 61\n", "model.metadata[\"citations_date\"] = \"2026-07-05\"\n" ] }, { "cell_type": "markdown", "id": "54a55994", "metadata": {}, "source": [ "## Download clock dependencies" ] }, { "cell_type": "code", "execution_count": 5, "id": "1fd58807", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T20:01:04.448613Z", "iopub.status.busy": "2026-07-04T20:01:04.448493Z", "iopub.status.idle": "2026-07-04T20:01:04.610452Z", "shell.execute_reply": "2026-07-04T20:01:04.609920Z" } }, "outputs": [ { "data": { "text/plain": [ "0" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "os.system(f\"curl -sL -o prostatecancerkirby.xlsx https://static-content.springer.com/esm/art%3A10.1186%2Fs12885-017-3252-2/MediaObjects/12885_2017_3252_MOESM4_ESM.xlsx\")" ] }, { "cell_type": "markdown", "id": "6fba8167", "metadata": {}, "source": [ "## Load features" ] }, { "cell_type": "code", "execution_count": 6, "id": "f5753676", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T20:01:04.611793Z", "iopub.status.busy": "2026-07-04T20:01:04.611688Z", "iopub.status.idle": "2026-07-04T20:01:04.682819Z", "shell.execute_reply": "2026-07-04T20:01:04.682348Z" } }, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "/Users/lucascamillo/pyaging/.venv/lib/python3.13/site-packages/openpyxl/worksheet/_reader.py:329: UserWarning: Unknown extension is not supported and will be removed\n", " warn(msg)\n" ] } ], "source": [ "raw = pd.read_excel('prostatecancerkirby.xlsx', sheet_name=0, header=None)\n", "hdr_cell = val_cell = None\n", "for i in range(len(raw)):\n", " for j in range(raw.shape[1]):\n", " c = str(raw.iloc[i, j])\n", " if '(Intercept)' in c and 'cg' in c:\n", " hdr_cell = c\n", " val_cell = str(raw.iloc[i + 1, j])\n", " break\n", " if hdr_cell:\n", " break\n", "names = hdr_cell.split()\n", "nums = [float(x) for x in val_cell.split()]\n", "intercept_value = 0.0\n", "feats, coefs = [], []\n", "for name, num in zip(names, nums):\n", " if 'Intercept' in name:\n", " intercept_value = num\n", " else:\n", " feats.append(name)\n", " coefs.append(num)\n", "model.features = feats" ] }, { "cell_type": "markdown", "id": "abef587e", "metadata": {}, "source": [ "## Load weights into base model" ] }, { "cell_type": "code", "execution_count": 7, "id": "033fa993", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T20:01:04.684168Z", "iopub.status.busy": "2026-07-04T20:01:04.684081Z", "iopub.status.idle": "2026-07-04T20:01:04.686271Z", "shell.execute_reply": "2026-07-04T20:01:04.685879Z" } }, "outputs": [], "source": [ "weights = torch.tensor(coefs).unsqueeze(0).float()\n", "intercept = torch.tensor([intercept_value]).float()" ] }, { "cell_type": "code", "execution_count": 8, "id": "b5266595", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T20:01:04.687494Z", "iopub.status.busy": "2026-07-04T20:01:04.687427Z", "iopub.status.idle": "2026-07-04T20:01:04.689681Z", "shell.execute_reply": "2026-07-04T20:01:04.689156Z" } }, "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": "ae2ea44c", "metadata": {}, "source": [ "## Load reference values" ] }, { "cell_type": "code", "execution_count": 9, "id": "9e2f57ff", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T20:01:04.691061Z", "iopub.status.busy": "2026-07-04T20:01:04.690973Z", "iopub.status.idle": "2026-07-04T20:01:04.692653Z", "shell.execute_reply": "2026-07-04T20:01:04.692259Z" } }, "outputs": [], "source": [ "model.reference_values = None" ] }, { "cell_type": "markdown", "id": "e03cc985", "metadata": {}, "source": [ "## Load preprocess and postprocess objects" ] }, { "cell_type": "code", "execution_count": 10, "id": "636576a0", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T20:01:04.693727Z", "iopub.status.busy": "2026-07-04T20:01:04.693661Z", "iopub.status.idle": "2026-07-04T20:01:04.695117Z", "shell.execute_reply": "2026-07-04T20:01:04.694820Z" } }, "outputs": [], "source": [ "model.preprocess_name = None\n", "model.preprocess_dependencies = None" ] }, { "cell_type": "code", "execution_count": 11, "id": "bbe0d70a", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T20:01:04.696276Z", "iopub.status.busy": "2026-07-04T20:01:04.696194Z", "iopub.status.idle": "2026-07-04T20:01:04.697894Z", "shell.execute_reply": "2026-07-04T20:01:04.697410Z" } }, "outputs": [], "source": [ "model.postprocess_name = None\n", "model.postprocess_dependencies = None" ] }, { "cell_type": "markdown", "id": "30c86da3", "metadata": {}, "source": [ "## Check all clock parameters" ] }, { "cell_type": "code", "execution_count": 12, "id": "8aa16777", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T20:01:04.699182Z", "iopub.status.busy": "2026-07-04T20:01:04.699100Z", "iopub.status.idle": "2026-07-04T20:01:04.702742Z", "shell.execute_reply": "2026-07-04T20:01:04.702328Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "%==================================== Model Details ====================================%\n", "Model Attributes:\n", "\n", "training: True\n", "metadata: {'approved_by_author': '⌛',\n", " 'citation': 'Kirby, Michael K., et al. \"Genome-wide DNA methylation '\n", " 'measurements in prostate tissues uncovers novel prostate cancer '\n", " 'diagnostic biomarkers and predictors of progression.\" BMC Cancer '\n", " '17.1 (2017): 273.',\n", " 'clock_name': 'prostatecancerkirby',\n", " 'data_type': 'methylation',\n", " 'doi': 'https://doi.org/10.1186/s12885-017-3252-2',\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: ['cg00054525', 'cg16794576', 'cg24581650']\n", "base_model_features: None\n", "\n", "%==================================== Model Details ====================================%\n", "Model Structure:\n", "\n", "base_model: LinearModel(\n", " (linear): Linear(in_features=3, out_features=1, bias=True)\n", ")\n", "\n", "%==================================== Model Details ====================================%\n", "Model Parameters and Weights:\n", "\n", "base_model.linear.weight: tensor([[-17.0370, 24.1830, -13.8250]])\n", "base_model.linear.bias: tensor([6.5240])\n", "\n", "%==================================== Model Details ====================================%\n", "\n" ] } ], "source": [ "pya.utils.print_model_details(model)" ] }, { "cell_type": "markdown", "id": "750d6998", "metadata": {}, "source": [ "## Basic test" ] }, { "cell_type": "code", "execution_count": 13, "id": "c6827524", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T20:01:04.704066Z", "iopub.status.busy": "2026-07-04T20:01:04.703985Z", "iopub.status.idle": "2026-07-04T20:01:04.708391Z", "shell.execute_reply": "2026-07-04T20:01:04.707965Z" } }, "outputs": [ { "data": { "text/plain": [ "tensor([[ 3.3665],\n", " [ 15.9152],\n", " [ -7.6545],\n", " [ 9.1350],\n", " [ 7.7513],\n", " [ 24.9928],\n", " [ -6.7956],\n", " [ 17.0494],\n", " [ 17.7305],\n", " [-18.3624]], 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": "85485e51", "metadata": {}, "source": [ "## Save torch model" ] }, { "cell_type": "code", "execution_count": 14, "id": "bfdbe168", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T20:01:04.709761Z", "iopub.status.busy": "2026-07-04T20:01:04.709681Z", "iopub.status.idle": "2026-07-04T20:01:04.713060Z", "shell.execute_reply": "2026-07-04T20:01:04.712563Z" } }, "outputs": [], "source": [ "torch.save(model, f\"../weights/{model.metadata['clock_name']}.pt\")" ] }, { "cell_type": "markdown", "id": "d00d59db", "metadata": {}, "source": [ "## Clear directory\n", "" ] }, { "cell_type": "code", "execution_count": 15, "id": "3181609a", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T20:01:04.714598Z", "iopub.status.busy": "2026-07-04T20:01:04.714510Z", "iopub.status.idle": "2026-07-04T20:01:04.719003Z", "shell.execute_reply": "2026-07-04T20:01:04.717784Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Deleted file: prostatecancerkirby.xlsx\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 }