{ "cells": [ { "cell_type": "markdown", "id": "2f04eee0-5928-4e74-a754-6dc2e528810c", "metadata": {}, "source": [ "# HRSInCHPhenoAge" ] }, { "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": "2025-04-07T17:51:58.091093Z", "iopub.status.busy": "2025-04-07T17:51:58.090949Z", "iopub.status.idle": "2025-04-07T17:51:59.474376Z", "shell.execute_reply": "2025-04-07T17:51:59.474003Z" } }, "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": "2025-04-07T17:51:59.476255Z", "iopub.status.busy": "2025-04-07T17:51:59.475975Z", "iopub.status.idle": "2025-04-07T17:51:59.484397Z", "shell.execute_reply": "2025-04-07T17:51:59.484055Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "class HRSInCHPhenoAge(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.HRSInCHPhenoAge)" ] }, { "cell_type": "code", "execution_count": 3, "id": "78536494-f1d9-44de-8583-c89a310d2307", "metadata": { "execution": { "iopub.execute_input": "2025-04-07T17:51:59.485911Z", "iopub.status.busy": "2025-04-07T17:51:59.485792Z", "iopub.status.idle": "2025-04-07T17:51:59.487551Z", "shell.execute_reply": "2025-04-07T17:51:59.487294Z" } }, "outputs": [], "source": [ "model = pya.models.HRSInCHPhenoAge()" ] }, { "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": "2025-04-07T17:51:59.488947Z", "iopub.status.busy": "2025-04-07T17:51:59.488830Z", "iopub.status.idle": "2025-04-07T17:51:59.490913Z", "shell.execute_reply": "2025-04-07T17:51:59.490638Z" } }, "outputs": [], "source": [ "model.metadata[\"clock_name\"] = \"hrsinchphenoage\"\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\"] = 2022\n", "model.metadata[\"approved_by_author\"] = \"⌛\"\n", "model.metadata[\"citation\"] = \"Higgins-Chen, Albert T., et al. \\\"A computational solution for bolstering reliability of epigenetic clocks: implications for clinical trials and longitudinal tracking.\\\" Nature Aging 2 (2022): 644–661.\"\n", "model.metadata[\"doi\"] = \"https://doi.org/10.1038/s43587-022-00248-2\"\n", "model.metadata[\"notes\"] = \"CpG-weighted HRS/InCHIANTI retraining of DNAm PhenoAge produced during the PC-clocks work; this implementation is not a principal-component clock.\"\n", "model.metadata[\"research_only\"] = None\n", "model.metadata[\"tissue\"] = [\"whole blood\"] # Paper: The HRS and InCHIANTI methylation training samples were blood samples.\n", "model.metadata[\"predicts\"] = [\"phenotypic age\"] # Paper: The function returns HRSInChPhenoAge.\n", "model.metadata[\"training_target\"] = [\"phenotypic age\"] # Paper: The retrained model is explicitly identified as PhenoAge.\n", "model.metadata[\"unit\"] = [\"years\"] # Paper: The returned PhenoAge estimate is on an age scale.\n", "model.metadata[\"model_type\"] = \"weighted linear score\" # Paper: The function multiplies beta values by fitted CpG weights and adds an intercept.\n", "model.metadata[\"platform\"] = [\"Illumina 450K\", \"Illumina EPIC\"] # Paper: HRS and InCHIANTI training data span EPIC and 450K methylation arrays.\n", "model.metadata[\"population\"] = \"adults\" # Paper: The function identifies HRS and InCHIANTI as the retraining data.\n", "model.metadata[\"journal\"] = \"Nature Aging\"\n", "model.metadata[\"last_author\"] = \"Morgan E. Levine\"\n", "model.metadata[\"n_features\"] = 959\n", "model.metadata[\"citations\"] = 497\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": "fe6c8887-fb81-4f5e-88d8-32fcd6c9d86a", "metadata": {}, "source": [ "#### Download GitHub repository" ] }, { "cell_type": "code", "execution_count": 5, "id": "1db3aa30-541d-4f78-b053-9868ce292ae8", "metadata": { "execution": { "iopub.execute_input": "2025-04-07T17:51:59.492327Z", "iopub.status.busy": "2025-04-07T17:51:59.492225Z", "iopub.status.idle": "2025-04-07T17:52:01.855717Z", "shell.execute_reply": "2025-04-07T17:52:01.855405Z" } }, "outputs": [ { "data": { "text/plain": [ "0" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "github_url = \"https://github.com/MorganLevineLab/methylCIPHER.git\"\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": "96782e2a-9084-4e4d-a459-7e98d2ec160c", "metadata": { "execution": { "iopub.execute_input": "2025-04-07T17:52:01.857214Z", "iopub.status.busy": "2025-04-07T17:52:01.857096Z", "iopub.status.idle": "2025-04-07T17:52:01.861183Z", "shell.execute_reply": "2025-04-07T17:52:01.860929Z" } }, "outputs": [], "source": [ "df = pd.read_csv('methylCIPHER/data-raw/HRSInChPhenoAge_CpG.csv')\n", "df['feature'] = df['CpG']\n", "df['coefficient'] = df['Weight']\n", "\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": "2025-04-07T17:52:01.862610Z", "iopub.status.busy": "2025-04-07T17:52:01.862513Z", "iopub.status.idle": "2025-04-07T17:52:01.864494Z", "shell.execute_reply": "2025-04-07T17:52:01.864262Z" } }, "outputs": [], "source": [ "weights = torch.tensor(df['coefficient'].tolist()).unsqueeze(0)\n", "intercept = torch.tensor([52.8334080])" ] }, { "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": "2025-04-07T17:52:01.865784Z", "iopub.status.busy": "2025-04-07T17:52:01.865698Z", "iopub.status.idle": "2025-04-07T17:52:01.867746Z", "shell.execute_reply": "2025-04-07T17:52:01.867487Z" } }, "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": "2025-04-07T17:52:01.869057Z", "iopub.status.busy": "2025-04-07T17:52:01.868972Z", "iopub.status.idle": "2025-04-07T17:52:01.870406Z", "shell.execute_reply": "2025-04-07T17:52:01.870123Z" } }, "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": "2025-04-07T17:52:01.871675Z", "iopub.status.busy": "2025-04-07T17:52:01.871592Z", "iopub.status.idle": "2025-04-07T17:52:01.872975Z", "shell.execute_reply": "2025-04-07T17:52:01.872728Z" } }, "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": "2025-04-07T17:52:01.874278Z", "iopub.status.busy": "2025-04-07T17:52:01.874177Z", "iopub.status.idle": "2025-04-07T17:52:01.875664Z", "shell.execute_reply": "2025-04-07T17:52:01.875423Z" } }, "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": "2025-04-07T17:52:01.877036Z", "iopub.status.busy": "2025-04-07T17:52:01.876945Z", "iopub.status.idle": "2025-04-07T17:52:01.880155Z", "shell.execute_reply": "2025-04-07T17:52:01.879913Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "%==================================== Model Details ====================================%\n", "Model Attributes:\n", "\n", "training: True\n", "metadata: {'approved_by_author': '⌛',\n", " 'citation': 'Higgins-Chen, Albert T., et al. \"A computational solution for '\n", " 'bolstering reliability of epigenetic clocks: Implications for '\n", " 'clinical trials and longitudinal tracking.\" Nature aging 2.7 '\n", " '(2022): 644-661.',\n", " 'clock_name': 'hrsinchphenoage',\n", " 'data_type': 'methylation',\n", " 'doi': 'https://doi.org/10.1038/s43587-022-00248-2',\n", " 'notes': None,\n", " 'research_only': None,\n", " 'species': 'Homo sapiens',\n", " 'version': None,\n", " 'year': 2022}\n", "reference_values: None\n", "preprocess_name: None\n", "preprocess_dependencies: None\n", "postprocess_name: None\n", "postprocess_dependencies: None\n", "features: ['cg00025138', 'cg00036347', 'cg00043599', 'cg00049440', 'cg00056497', 'cg00059225', 'cg00066239', 'cg00067518', 'cg00101154', 'cg00135293', 'cg00137209', 'cg00211115', 'cg00238295', 'cg00276799', 'cg00282953', 'cg00312921', 'cg00376639', 'cg00401091', 'cg00417823', 'cg00448560', 'cg00481159', 'cg00495693', 'cg00503840', 'cg00509996', 'cg00551910', 'cg00574958', 'cg00593462', 'cg00602811', 'cg00615241', 'cg00618626']... [Total elements: 959]\n", "base_model_features: None\n", "\n", "%==================================== Model Details ====================================%\n", "Model Structure:\n", "\n", "base_model: LinearModel(\n", " (linear): Linear(in_features=959, out_features=1, bias=True)\n", ")\n", "\n", "%==================================== Model Details ====================================%\n", "Model Parameters and Weights:\n", "\n", "base_model.linear.weight: [-12.598388671875, 2.0095407962799072, 3.08774995803833, 1.5167790651321411, 0.20355011522769928, 1.68230140209198, -1.249173879623413, -0.8185797333717346, 0.4907846450805664, 0.5390154123306274, 15.449186325073242, -1.285083293914795, -0.7427912354469299, 1.5232256650924683, 0.5885316729545593, 2.078218936920166, 3.4780304431915283, -10.69495964050293, 2.9323976039886475, -5.428037166595459, 0.2791459858417511, -0.285178542137146, 0.9086608290672302, -0.1606019139289856, 1.7213571071624756, -5.501366138458252, 0.08092798292636871, -2.233879566192627, -1.4966527223587036, -4.973464488983154]... [Tensor of shape torch.Size([1, 959])]\n", "base_model.linear.bias: tensor([52.8334])\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": "2025-04-07T17:52:01.881643Z", "iopub.status.busy": "2025-04-07T17:52:01.881477Z", "iopub.status.idle": "2025-04-07T17:52:01.885640Z", "shell.execute_reply": "2025-04-07T17:52:01.885358Z" } }, "outputs": [ { "data": { "text/plain": [ "tensor([[ 319.0174],\n", " [ -70.3330],\n", " [ 49.5369],\n", " [ -66.2511],\n", " [ -99.2095],\n", " [-165.9214],\n", " [ 160.0792],\n", " [ 293.2276],\n", " [ 181.4062],\n", " [-175.9353]], 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": "2025-04-07T17:52:01.886981Z", "iopub.status.busy": "2025-04-07T17:52:01.886898Z", "iopub.status.idle": "2025-04-07T17:52:01.889863Z", "shell.execute_reply": "2025-04-07T17:52:01.889621Z" } }, "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": "2025-04-07T17:52:01.891168Z", "iopub.status.busy": "2025-04-07T17:52:01.891078Z", "iopub.status.idle": "2025-04-07T17:52:01.908268Z", "shell.execute_reply": "2025-04-07T17:52:01.907907Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Deleted folder: methylCIPHER\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.7" } }, "nbformat": 4, "nbformat_minor": 5 }