{ "cells": [ { "cell_type": "markdown", "id": "2f04eee0-5928-4e74-a754-6dc2e528810c", "metadata": {}, "source": [ "# Hannum" ] }, { "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": { "execution": { "iopub.execute_input": "2024-03-05T20:17:31.722332Z", "iopub.status.busy": "2024-03-05T20:17:31.721892Z", "iopub.status.idle": "2024-03-05T20:17:33.055109Z", "shell.execute_reply": "2024-03-05T20:17:33.054815Z" } }, "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": { "execution": { "iopub.execute_input": "2024-03-05T20:17:33.057028Z", "iopub.status.busy": "2024-03-05T20:17:33.056855Z", "iopub.status.idle": "2024-03-05T20:17:33.064088Z", "shell.execute_reply": "2024-03-05T20:17:33.063821Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "class Hannum(pyagingModel):\n", " def __init__(self):\n", " super().__init__()\n", "\n", " def preprocess(self, x):\n", " return x\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.Hannum)" ] }, { "cell_type": "code", "execution_count": 3, "id": "78536494-f1d9-44de-8583-c89a310d2307", "metadata": { "execution": { "iopub.execute_input": "2024-03-05T20:17:33.065646Z", "iopub.status.busy": "2024-03-05T20:17:33.065563Z", "iopub.status.idle": "2024-03-05T20:17:33.067132Z", "shell.execute_reply": "2024-03-05T20:17:33.066903Z" } }, "outputs": [], "source": [ "model = pya.models.Hannum()" ] }, { "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": { "execution": { "iopub.execute_input": "2024-03-05T20:17:33.068611Z", "iopub.status.busy": "2024-03-05T20:17:33.068525Z", "iopub.status.idle": "2024-03-05T20:17:33.070423Z", "shell.execute_reply": "2024-03-05T20:17:33.070185Z" } }, "outputs": [], "source": [ "model.metadata[\"clock_name\"] = \"hannum\"\n", "model.metadata[\"data_type\"] = \"DNA methylation\" # Paper: The model uses genome-wide CpG methylation fractions.\n", "model.metadata[\"species\"] = \"Homo sapiens\" # Paper: The cohorts contained 656 human participants.\n", "model.metadata[\"year\"] = 2013\n", "model.metadata[\"approved_by_author\"] = \"⌛\"\n", "model.metadata[\"citation\"] = \"Hannum, G., et al. “Genome-wide methylation profiles reveal quantitative views of human aging rates.” Molecular Cell 49(2), 359–367 (2013).\"\n", "model.metadata[\"doi\"] = \"https://doi.org/10.1016/j.molcel.2012.10.016\"\n", "model.metadata[\"notes\"] = \"Whole-blood elastic-net predictor of chronological age from 71 CpG methylation fractions, derived in a 482-person primary cohort and validated in 174 independent participants.\"\n", "model.metadata[\"research_only\"] = None\n", "model.metadata[\"tissue\"] = [\"whole blood\"] # Paper: Samples were taken as whole blood.\n", "model.metadata[\"predicts\"] = [\"chronological age\"] # Paper: The model was built to predict participant age.\n", "model.metadata[\"training_target\"] = [\"chronological age\"] # Paper: Age was the response in the predictive aging model.\n", "model.metadata[\"unit\"] = [\"years\"] # Paper: The packaged linear model returns predicted age directly in years with no postprocessing transform.\n", "model.metadata[\"model_type\"] = \"elastic net regression\" # Paper: The predictive model used penalized multivariate regression known as Elastic Net.\n", "model.metadata[\"platform\"] = [\"Illumina 450K\"] # Paper: Whole-blood samples were processed on the Infinium HumanMethylation450 BeadChip.\n", "model.metadata[\"population\"] = \"adults\" # Paper: Two cohorts totaled 656 participants aged 19–101 years, comprising 426 Caucasian and 230 Hispanic individuals.\n", "model.metadata[\"journal\"] = \"Molecular Cell\"\n", "model.metadata[\"last_author\"] = \"Kang Zhang\"\n", "model.metadata[\"n_features\"] = 71\n", "model.metadata[\"citations\"] = 4501\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": "fbacbbc5-7cf1-41bd-81c4-45adde992de6", "metadata": {}, "source": [ "#### Download directly with curl" ] }, { "cell_type": "code", "execution_count": 5, "id": "348e113d-a00a-481d-84ac-e8459a4a5050", "metadata": { "execution": { "iopub.execute_input": "2024-03-05T20:17:33.071913Z", "iopub.status.busy": "2024-03-05T20:17:33.071827Z", "iopub.status.idle": "2024-03-05T20:17:33.397023Z", "shell.execute_reply": "2024-03-05T20:17:33.396025Z" } }, "outputs": [ { "data": { "text/plain": [ "0" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "supplementary_url = \"https://ars.els-cdn.com/content/image/1-s2.0-S1097276512008933-mmc2.xlsx\"\n", "supplementary_file_name = \"coefficients.xlsx\"\n", "os.system(f\"curl -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 Excel file" ] }, { "cell_type": "code", "execution_count": 6, "id": "110a5ded-d25f-4cef-8e84-4f51210dfc26", "metadata": { "execution": { "iopub.execute_input": "2024-03-05T20:17:33.402355Z", "iopub.status.busy": "2024-03-05T20:17:33.402007Z", "iopub.status.idle": "2024-03-05T20:17:33.538525Z", "shell.execute_reply": "2024-03-05T20:17:33.538215Z" } }, "outputs": [], "source": [ "df = pd.read_excel('coefficients.xlsx')\n", "df['feature'] = df['Marker']\n", "df['coefficient'] = df['Coefficient']\n", "model.features = df['feature'].tolist()" ] }, { "cell_type": "markdown", "id": "ee6d8fa0-4767-4c45-9717-eb1c95e2ddc0", "metadata": {}, "source": [ "## Load weights into base model" ] }, { "cell_type": "code", "execution_count": 7, "id": "e09b3463-4fd4-41b1-ac21-e63ddd223fe0", "metadata": { "execution": { "iopub.execute_input": "2024-03-05T20:17:33.540314Z", "iopub.status.busy": "2024-03-05T20:17:33.540231Z", "iopub.status.idle": "2024-03-05T20:17:33.542091Z", "shell.execute_reply": "2024-03-05T20:17:33.541845Z" } }, "outputs": [], "source": [ "weights = torch.tensor(df['coefficient'].tolist()).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": 8, "id": "d7f43b99-26f2-4622-9a76-316712058877", "metadata": { "execution": { "iopub.execute_input": "2024-03-05T20:17:33.543627Z", "iopub.status.busy": "2024-03-05T20:17:33.543521Z", "iopub.status.idle": "2024-03-05T20:17:33.545468Z", "shell.execute_reply": "2024-03-05T20:17:33.545236Z" } }, "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": "ad8b4c1d-9d57-48b7-9a30-bcfea7b747b1", "metadata": {}, "source": [ "## Load reference values" ] }, { "cell_type": "code", "execution_count": 9, "id": "ade0f4c9-2298-4fc3-bb72-d200907dd731", "metadata": { "execution": { "iopub.execute_input": "2024-03-05T20:17:33.546937Z", "iopub.status.busy": "2024-03-05T20:17:33.546846Z", "iopub.status.idle": "2024-03-05T20:17:33.548242Z", "shell.execute_reply": "2024-03-05T20:17:33.548028Z" } }, "outputs": [], "source": [ "model.reference_values = None" ] }, { "cell_type": "markdown", "id": "af3bcf7b-74a8-4d21-9ccb-4de0c2b0516b", "metadata": {}, "source": [ "## Load preprocess and postprocess objects" ] }, { "cell_type": "code", "execution_count": 10, "id": "7a22fb20-c605-424d-8efb-7620c2c0755c", "metadata": { "execution": { "iopub.execute_input": "2024-03-05T20:17:33.549643Z", "iopub.status.busy": "2024-03-05T20:17:33.549572Z", "iopub.status.idle": "2024-03-05T20:17:33.551035Z", "shell.execute_reply": "2024-03-05T20:17:33.550799Z" } }, "outputs": [], "source": [ "model.preprocess_name = None\n", "model.preprocess_dependencies = None" ] }, { "cell_type": "code", "execution_count": 11, "id": "ff4a21cb-cf41-44dc-9ed1-95cf8aa15772", "metadata": { "execution": { "iopub.execute_input": "2024-03-05T20:17:33.552333Z", "iopub.status.busy": "2024-03-05T20:17:33.552263Z", "iopub.status.idle": "2024-03-05T20:17:33.553644Z", "shell.execute_reply": "2024-03-05T20:17:33.553416Z" } }, "outputs": [], "source": [ "model.postprocess_name = None\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": 12, "id": "2168355c-47d9-475d-b816-49f65e74887c", "metadata": { "execution": { "iopub.execute_input": "2024-03-05T20:17:33.555024Z", "iopub.status.busy": "2024-03-05T20:17:33.554949Z", "iopub.status.idle": "2024-03-05T20:17:33.557262Z", "shell.execute_reply": "2024-03-05T20:17:33.557027Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "%==================================== Model Details ====================================%\n", "Model Attributes:\n", "\n", "training: True\n", "metadata: {'approved_by_author': '⌛',\n", " 'citation': ('Hannum, Gregory, et al. \"Genome-wide methylation profiles '\n", " 'reveal quantitative views of human aging rates.\" Molecular cell '\n", " '49.2 (2013): 359-367.',),\n", " 'clock_name': 'hannum',\n", " 'data_type': 'methylation',\n", " 'doi': 'https://doi.org/10.1016/j.molcel.2012.10.016',\n", " 'notes': None,\n", " 'research_only': None,\n", " 'species': 'Homo sapiens',\n", " 'version': None,\n", " 'year': 2013}\n", "reference_values: None\n", "preprocess_name: None\n", "preprocess_dependencies: None\n", "postprocess_name: None\n", "postprocess_dependencies: None\n", "features: ['cg20822990', 'cg22512670', 'cg25410668', 'cg04400972', 'cg16054275', 'cg10501210', 'cg09809672', 'ch.2.30415474F', 'cg22158769', 'cg02085953', 'cg06639320', 'cg22454769', 'cg24079702', 'cg23606718', 'cg22016779', 'cg04474832', 'cg03607117', 'cg07553761', 'cg00481951', 'cg25478614', 'cg25428494', 'cg02650266', 'cg08234504', 'cg23500537', 'cg20052760', 'cg16867657', 'cg22736354', 'cg06493994', 'cg06685111', 'cg00486113']... [Total elements: 71]\n", "base_model_features: None\n", "\n", "%==================================== Model Details ====================================%\n", "Model Structure:\n", "\n", "base_model: LinearModel(\n", " (linear): Linear(in_features=71, out_features=1, bias=True)\n", ")\n", "\n", "%==================================== Model Details ====================================%\n", "Model Parameters and Weights:\n", "\n", "base_model.linear.weight: [-15.699999809265137, 1.0499999523162842, 3.869999885559082, 9.619999885559082, -11.100000381469727, -6.460000038146973, -0.7400000095367432, 5.789999961853027, -2.059999942779541, 1.0199999809265137, 8.949999809265137, 4.849999904632568, 2.4800000190734863, 8.350000381469727, 1.7899999618530273, -7.099999904632568, 10.699999809265137, 3.7200000286102295, -2.7200000286102295, 4.010000228881836, -1.809999942779541, 10.199999809265137, -3.1600000858306885, 5.670000076293945, -12.600000381469727, 10.800000190734863, 4.420000076293945, 9.420000076293945, -13.100000381469727, -10.699999809265137]... [Tensor of shape torch.Size([1, 71])]\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": 13, "id": "936b9877-d076-4ced-99aa-e8d4c58c5caf", "metadata": { "execution": { "iopub.execute_input": "2024-03-05T20:17:33.558774Z", "iopub.status.busy": "2024-03-05T20:17:33.558701Z", "iopub.status.idle": "2024-03-05T20:17:33.562205Z", "shell.execute_reply": "2024-03-05T20:17:33.561986Z" } }, "outputs": [ { "data": { "text/plain": [ "tensor([[ 78.6234],\n", " [ 7.5513],\n", " [172.7843],\n", " [ 43.1732],\n", " [145.3521],\n", " [ 79.6871],\n", " [ 75.0541],\n", " [ 41.7890],\n", " [-12.6555],\n", " [-78.9716]], 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": "fe8299d7-9285-4e22-82fd-b664434b4369", "metadata": {}, "source": [ "## Save torch model" ] }, { "cell_type": "code", "execution_count": 14, "id": "5ef2fa8d-c80b-4fdd-8555-79c0d541788e", "metadata": { "execution": { "iopub.execute_input": "2024-03-05T20:17:33.563720Z", "iopub.status.busy": "2024-03-05T20:17:33.563633Z", "iopub.status.idle": "2024-03-05T20:17:33.565710Z", "shell.execute_reply": "2024-03-05T20:17:33.565467Z" } }, "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": 15, "id": "11aeaa70-44c0-42f9-86d7-740e3849a7a6", "metadata": { "execution": { "iopub.execute_input": "2024-03-05T20:17:33.567125Z", "iopub.status.busy": "2024-03-05T20:17:33.567039Z", "iopub.status.idle": "2024-03-05T20:17:33.569966Z", "shell.execute_reply": "2024-03-05T20:17:33.569731Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Deleted file: coefficients.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": "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 }