{ "cells": [ { "cell_type": "markdown", "id": "2f04eee0-5928-4e74-a754-6dc2e528810c", "metadata": {}, "source": [ "# PedBE" ] }, { "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-05T21:22:59.472571Z", "iopub.status.busy": "2024-03-05T21:22:59.471909Z", "iopub.status.idle": "2024-03-05T21:23:07.530181Z", "shell.execute_reply": "2024-03-05T21:23:07.529871Z" } }, "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-05T21:23:07.532131Z", "iopub.status.busy": "2024-03-05T21:23:07.531963Z", "iopub.status.idle": "2024-03-05T21:23:07.543752Z", "shell.execute_reply": "2024-03-05T21:23:07.543460Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "class PedBE(pyagingModel):\n", " def __init__(self):\n", " super().__init__()\n", "\n", " def preprocess(self, x):\n", " return x\n", "\n", " def postprocess(self, x):\n", " \"\"\"\n", " Applies an anti-logarithmic linear transformation to a PyTorch tensor.\n", " \"\"\"\n", " adult_age = 20\n", "\n", " # Create a mask for negative and non-negative values\n", " mask_negative = x < 0\n", " mask_non_negative = ~mask_negative\n", "\n", " # Initialize the result tensor\n", " age_tensor = torch.empty_like(x)\n", "\n", " # Exponential transformation for negative values\n", " age_tensor[mask_negative] = (1 + adult_age) * torch.exp(x[mask_negative]) - 1\n", "\n", " # Linear transformation for non-negative values\n", " age_tensor[mask_non_negative] = (1 + adult_age) * x[\n", " mask_non_negative\n", " ] + adult_age\n", "\n", " return age_tensor\n", "\n" ] } ], "source": [ "def print_entire_class(cls):\n", " source = inspect.getsource(cls)\n", " print(source)\n", "\n", "print_entire_class(pya.models.PedBE)" ] }, { "cell_type": "code", "execution_count": 3, "id": "78536494-f1d9-44de-8583-c89a310d2307", "metadata": { "execution": { "iopub.execute_input": "2024-03-05T21:23:07.545288Z", "iopub.status.busy": "2024-03-05T21:23:07.545179Z", "iopub.status.idle": "2024-03-05T21:23:07.547193Z", "shell.execute_reply": "2024-03-05T21:23:07.546706Z" } }, "outputs": [], "source": [ "model = pya.models.PedBE()" ] }, { "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-05T21:23:07.548978Z", "iopub.status.busy": "2024-03-05T21:23:07.548877Z", "iopub.status.idle": "2024-03-05T21:23:07.551163Z", "shell.execute_reply": "2024-03-05T21:23:07.550761Z" } }, "outputs": [], "source": [ "model.metadata[\"clock_name\"] = \"pedbe\"\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\"] = \"McEwen, Lisa M., et al. \\\"The PedBE clock accurately estimates DNA methylation age in pediatric buccal cells.\\\" Proceedings of the National Academy of Sciences 117 (2020): 23329–23335.\"\n", "model.metadata[\"doi\"] = \"https://doi.org/10.1073/pnas.1820843116\"\n", "model.metadata[\"notes\"] = \"Pediatric chronological-age estimator developed specifically for noninvasive buccal epithelial-cell samples.\"\n", "model.metadata[\"research_only\"] = None\n", "model.metadata[\"tissue\"] = [\"buccal epithelium\"] # Paper: The model was developed and tested in buccal epithelial cells.\n", "model.metadata[\"predicts\"] = [\"chronological age\"] # Paper: PedBE estimates DNA methylation age in children.\n", "model.metadata[\"training_target\"] = [\"chronological age\"] # Paper: Elastic-net regression selected CpGs predictive of participant age.\n", "model.metadata[\"unit\"] = [\"years\"] # Paper: Age prediction errors and estimates are reported in years.\n", "model.metadata[\"model_type\"] = \"elastic net regression\" # Paper: The clock was developed using elastic-net penalized regression.\n", "model.metadata[\"platform\"] = [\"Illumina 450K\", \"Illumina EPIC\"] # Paper: The pooled pediatric buccal cohorts included 450K and EPIC methylation profiles.\n", "model.metadata[\"population\"] = \"children and adolescents\" # Paper: The study included 1,721 healthy individuals aged 0 to 20 years.\n", "model.metadata[\"journal\"] = \"Proceedings of the National Academy of Sciences of the United States of America\"\n", "model.metadata[\"last_author\"] = \"Michael S. Kobor\"\n", "model.metadata[\"n_features\"] = 94\n", "model.metadata[\"citations\"] = 292\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": "f198b190-7f60-42a0-a23a-a88bbb60fb2f", "metadata": {}, "source": [ "#### Download GitHub repository" ] }, { "cell_type": "code", "execution_count": 5, "id": "4274d190-b549-47b6-9c3e-b2cf90547bec", "metadata": { "execution": { "iopub.execute_input": "2024-03-05T21:23:07.552952Z", "iopub.status.busy": "2024-03-05T21:23:07.552850Z", "iopub.status.idle": "2024-03-05T21:23:08.374551Z", "shell.execute_reply": "2024-03-05T21:23:08.374032Z" } }, "outputs": [ { "data": { "text/plain": [ "0" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "github_url = \"https://github.com/kobor-lab/Public-Scripts\"\n", "github_folder_name = github_url.split('/')[-1].split('.')[0]\n", "os.system(f\"git clone {github_url}\")" ] }, { "cell_type": "markdown", "id": "5035b180-3d1b-4432-8ebe-b9c92bd93a7f", "metadata": {}, "source": [ "## Load features" ] }, { "cell_type": "markdown", "id": "15f4af76-b93c-438c-b57f-f129d6e9ec99", "metadata": {}, "source": [ "#### From CSV file" ] }, { "cell_type": "code", "execution_count": 6, "id": "8a3d5de6-6303-487a-8b4d-e6345792f7be", "metadata": { "execution": { "iopub.execute_input": "2024-03-05T21:23:08.377866Z", "iopub.status.busy": "2024-03-05T21:23:08.377678Z", "iopub.status.idle": "2024-03-05T21:23:08.384082Z", "shell.execute_reply": "2024-03-05T21:23:08.383667Z" } }, "outputs": [], "source": [ "df = pd.read_csv('Public-Scripts/datcoefInteresting94.csv')\n", "df['feature'] = df['ID']\n", "df['coefficient'] = df['Coef']\n", "\n", "model.features = df['feature'][1:].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-05T21:23:08.386513Z", "iopub.status.busy": "2024-03-05T21:23:08.386357Z", "iopub.status.idle": "2024-03-05T21:23:08.389361Z", "shell.execute_reply": "2024-03-05T21:23:08.388947Z" } }, "outputs": [], "source": [ "weights = torch.tensor(df['coefficient'][1:].tolist()).unsqueeze(0)\n", "intercept = torch.tensor([df['coefficient'][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-05T21:23:08.391644Z", "iopub.status.busy": "2024-03-05T21:23:08.391500Z", "iopub.status.idle": "2024-03-05T21:23:08.394629Z", "shell.execute_reply": "2024-03-05T21:23:08.394230Z" } }, "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-05T21:23:08.396857Z", "iopub.status.busy": "2024-03-05T21:23:08.396715Z", "iopub.status.idle": "2024-03-05T21:23:08.398669Z", "shell.execute_reply": "2024-03-05T21:23:08.398344Z" } }, "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-05T21:23:08.400633Z", "iopub.status.busy": "2024-03-05T21:23:08.400512Z", "iopub.status.idle": "2024-03-05T21:23:08.402307Z", "shell.execute_reply": "2024-03-05T21:23:08.402009Z" } }, "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-05T21:23:08.404008Z", "iopub.status.busy": "2024-03-05T21:23:08.403894Z", "iopub.status.idle": "2024-03-05T21:23:08.405684Z", "shell.execute_reply": "2024-03-05T21:23:08.405384Z" } }, "outputs": [], "source": [ "model.postprocess_name = 'anti_log_linear'\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-05T21:23:08.407437Z", "iopub.status.busy": "2024-03-05T21:23:08.407323Z", "iopub.status.idle": "2024-03-05T21:23:08.410733Z", "shell.execute_reply": "2024-03-05T21:23:08.410407Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "%==================================== Model Details ====================================%\n", "Model Attributes:\n", "\n", "training: True\n", "metadata: {'approved_by_author': '⌛',\n", " 'citation': 'McEwen, Lisa M., et al. \"The PedBE clock accurately estimates '\n", " 'DNA methylation age in pediatric buccal cells.\" Proceedings of '\n", " 'the National Academy of Sciences 117.38 (2020): 23329-23335.',\n", " 'clock_name': 'pedbe',\n", " 'data_type': 'methylation',\n", " 'doi': 'https://doi.org/10.1073/pnas.1820843116',\n", " 'notes': None,\n", " 'research_only': None,\n", " 'species': 'Homo sapiens',\n", " 'version': None,\n", " 'year': 2019}\n", "reference_values: None\n", "preprocess_name: None\n", "preprocess_dependencies: None\n", "postprocess_name: 'anti_log_linear'\n", "postprocess_dependencies: None\n", "features: ['cg00059225', 'cg00085493', 'cg00095976', 'cg00609333', 'cg01287592', 'cg01704999', 'cg02209075', 'cg02310103', 'cg02426178', 'cg02821342', 'cg02980055', 'cg03020208', 'cg03466124', 'cg03473016', 'cg03493146', 'cg03555227', 'cg04221461', 'cg04452203', 'cg04937184', 'cg04948475', 'cg05024939', 'cg05271255', 'cg05923197', 'cg05928290', 'cg06048436', 'cg06144905', 'cg06198384', 'cg06416491', 'cg06430061', 'cg06455149']... [Total elements: 94]\n", "base_model_features: None\n", "\n", "%==================================== Model Details ====================================%\n", "Model Structure:\n", "\n", "base_model: LinearModel(\n", " (linear): Linear(in_features=94, out_features=1, bias=True)\n", ")\n", "\n", "%==================================== Model Details ====================================%\n", "Model Parameters and Weights:\n", "\n", "base_model.linear.weight: [0.021960020065307617, -0.10039610415697098, 0.007872418500483036, 0.022823642939329147, -0.055414702743291855, -0.09757450968027115, 0.13820089399814606, -0.08401073515415192, -0.3583613932132721, -0.13026674091815948, -0.1387656182050705, 0.21038542687892914, -0.022311074659228325, 0.00015541094762738794, -0.1624089926481247, 0.6385841369628906, 0.03457474708557129, -0.026989279314875603, -0.05423707515001297, -0.0008215174311771989, 0.14885476231575012, -0.1249200701713562, 0.039291542023420334, 0.15890249609947205, -0.1548999398946762, 0.31524088978767395, 0.003525394480675459, -0.19241906702518463, -0.017204945906996727, 0.08637607842683792]... [Tensor of shape torch.Size([1, 94])]\n", "base_model.linear.bias: tensor([-2.0973])\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-05T21:23:08.412500Z", "iopub.status.busy": "2024-03-05T21:23:08.412403Z", "iopub.status.idle": "2024-03-05T21:23:08.416297Z", "shell.execute_reply": "2024-03-05T21:23:08.416029Z" } }, "outputs": [ { "data": { "text/plain": [ "tensor([[-0.8260],\n", " [-0.4025],\n", " [ 2.6240],\n", " [-0.3707],\n", " [-0.8111],\n", " [-0.4591],\n", " [16.2847],\n", " [ 8.2621],\n", " [ 2.4227],\n", " [ 4.0783]], 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-05T21:23:08.417959Z", "iopub.status.busy": "2024-03-05T21:23:08.417848Z", "iopub.status.idle": "2024-03-05T21:23:08.421051Z", "shell.execute_reply": "2024-03-05T21:23:08.420790Z" } }, "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-05T21:23:08.422543Z", "iopub.status.busy": "2024-03-05T21:23:08.422459Z", "iopub.status.idle": "2024-03-05T21:23:08.428060Z", "shell.execute_reply": "2024-03-05T21:23:08.427839Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Deleted folder: Public-Scripts\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", "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.17" } }, "nbformat": 4, "nbformat_minor": 5 }