{ "cells": [ { "cell_type": "markdown", "id": "2f04eee0-5928-4e74-a754-6dc2e528810c", "metadata": {}, "source": [ "# cABEC" ] }, { "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:47:38.148991Z", "iopub.status.busy": "2025-04-07T17:47:38.148632Z", "iopub.status.idle": "2025-04-07T17:47:39.485346Z", "shell.execute_reply": "2025-04-07T17:47:39.485036Z" } }, "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:47:39.487085Z", "iopub.status.busy": "2025-04-07T17:47:39.486868Z", "iopub.status.idle": "2025-04-07T17:47:39.497806Z", "shell.execute_reply": "2025-04-07T17:47:39.497526Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "class cABEC(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.cABEC)" ] }, { "cell_type": "code", "execution_count": 3, "id": "78536494-f1d9-44de-8583-c89a310d2307", "metadata": { "execution": { "iopub.execute_input": "2025-04-07T17:47:39.499103Z", "iopub.status.busy": "2025-04-07T17:47:39.499019Z", "iopub.status.idle": "2025-04-07T17:47:39.500652Z", "shell.execute_reply": "2025-04-07T17:47:39.500411Z" } }, "outputs": [], "source": [ "model = pya.models.cABEC()" ] }, { "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:47:39.501956Z", "iopub.status.busy": "2025-04-07T17:47:39.501875Z", "iopub.status.idle": "2025-04-07T17:47:39.503827Z", "shell.execute_reply": "2025-04-07T17:47:39.503591Z" } }, "outputs": [], "source": [ "model.metadata[\"clock_name\"] = \"cabec\"\n", "model.metadata[\"data_type\"] = \"DNA methylation\" # Paper: The model is based on DNA methylation measurements.\n", "model.metadata[\"species\"] = \"Homo sapiens\" # Paper: The study samples are Homo sapiens.\n", "model.metadata[\"year\"] = 2020\n", "model.metadata[\"approved_by_author\"] = \"⌛\"\n", "model.metadata[\"citation\"] = \"Lee, Yunsung, et al. \\\"Blood-based epigenetic estimators of chronological age in human adults using DNA methylation data from the Illumina MethylationEPIC array.\\\" BMC genomics 21 (2020): 1-13.\"\n", "model.metadata[\"doi\"] = \"https://doi.org/10.1186/s12864-020-07168-8\"\n", "model.metadata[\"notes\"] = \"Common Adult Blood-based EPIC Clock trained on the extended adult whole-blood dataset but restricted to autosomal CpGs shared by the Illumina 450K and EPIC arrays.\"\n", "model.metadata[\"research_only\"] = None\n", "model.metadata[\"tissue\"] = [\"whole blood\"] # Paper: The listed tissue is the model-development sample material.\n", "model.metadata[\"predicts\"] = [\"chronological age\"] # Paper: The reported predictor output is chronological age.\n", "model.metadata[\"training_target\"] = [\"chronological age\"] # Paper: The fitting outcome is chronological age.\n", "model.metadata[\"unit\"] = [\"years\"] # Paper: The returned construct is expressed as years.\n", "model.metadata[\"model_type\"] = \"elastic net regression\" # Paper: The clock was fitted using Elastic net.\n", "model.metadata[\"platform\"] = [\"Illumina 450K\", \"Illumina EPIC\"] # Paper: Training/selection used Illumina 450K/EPIC common probes.\n", "model.metadata[\"population\"] = \"adults\" # Paper: adults aged 18–88 years (MoBa-START plus GEO; n=2,227)\n", "model.metadata[\"journal\"] = \"BMC Genomics\"\n", "model.metadata[\"last_author\"] = \"Jon Bohlin\"\n", "model.metadata[\"n_features\"] = 1892\n", "model.metadata[\"citations\"] = 21\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": "9a5b163b-1b25-4c2f-ad0c-86f0f2ed39d0", "metadata": {}, "source": [ "#### Download directly with curl" ] }, { "cell_type": "code", "execution_count": 5, "id": "28fdcad4-1f62-4da7-b556-1ecc8cf3d0e0", "metadata": { "execution": { "iopub.execute_input": "2025-04-07T17:47:39.505155Z", "iopub.status.busy": "2025-04-07T17:47:39.505074Z", "iopub.status.idle": "2025-04-07T17:47:39.742061Z", "shell.execute_reply": "2025-04-07T17:47:39.740755Z" } }, "outputs": [ { "data": { "text/plain": [ "0" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "supplementary_url = \"https://static-content.springer.com/esm/art%3A10.1186%2Fs12864-020-07168-8/MediaObjects/12864_2020_7168_MOESM1_ESM.csv\"\n", "supplementary_file_name = \"coefficients.csv\"\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": "15f4af76-b93c-438c-b57f-f129d6e9ec99", "metadata": {}, "source": [ "#### From CSV file" ] }, { "cell_type": "code", "execution_count": 6, "id": "ec85c728", "metadata": { "execution": { "iopub.execute_input": "2025-04-07T17:47:39.745542Z", "iopub.status.busy": "2025-04-07T17:47:39.745236Z", "iopub.status.idle": "2025-04-07T17:47:39.776586Z", "shell.execute_reply": "2025-04-07T17:47:39.776098Z" } }, "outputs": [], "source": [ "df = pd.read_csv('coefficients.csv', index_col=0)\n", "df = df[~df['cABEC_coefficient'].isna()]\n", "df['feature'] = df.index.tolist()\n", "df['coefficient'] = df['cABEC_coefficient']\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": "2025-04-07T17:47:39.778969Z", "iopub.status.busy": "2025-04-07T17:47:39.778792Z", "iopub.status.idle": "2025-04-07T17:47:39.782190Z", "shell.execute_reply": "2025-04-07T17:47:39.781793Z" } }, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ ":2: FutureWarning: Series.__getitem__ treating keys as positions is deprecated. In a future version, integer keys will always be treated as labels (consistent with DataFrame behavior). To access a value by position, use `ser.iloc[pos]`\n", " intercept = torch.tensor([df['coefficient'][0]])\n" ] } ], "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": "2025-04-07T17:47:39.784061Z", "iopub.status.busy": "2025-04-07T17:47:39.783924Z", "iopub.status.idle": "2025-04-07T17:47:39.786867Z", "shell.execute_reply": "2025-04-07T17:47:39.786487Z" } }, "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": "86de757f-fb38-4bcb-b91e-fc3372d22aad", "metadata": { "execution": { "iopub.execute_input": "2025-04-07T17:47:39.788548Z", "iopub.status.busy": "2025-04-07T17:47:39.788414Z", "iopub.status.idle": "2025-04-07T17:47:39.790323Z", "shell.execute_reply": "2025-04-07T17:47:39.789966Z" } }, "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:47:39.792038Z", "iopub.status.busy": "2025-04-07T17:47:39.791896Z", "iopub.status.idle": "2025-04-07T17:47:39.793716Z", "shell.execute_reply": "2025-04-07T17:47:39.793381Z" } }, "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:47:39.795236Z", "iopub.status.busy": "2025-04-07T17:47:39.795105Z", "iopub.status.idle": "2025-04-07T17:47:39.796883Z", "shell.execute_reply": "2025-04-07T17:47:39.796559Z" } }, "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:47:39.798476Z", "iopub.status.busy": "2025-04-07T17:47:39.798349Z", "iopub.status.idle": "2025-04-07T17:47:39.802308Z", "shell.execute_reply": "2025-04-07T17:47:39.801983Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "%==================================== Model Details ====================================%\n", "Model Attributes:\n", "\n", "training: True\n", "metadata: {'approved_by_author': '⌛',\n", " 'citation': 'Lee, Yunsung, et al. \"Blood-based epigenetic estimators of '\n", " 'chronological age in human adults using DNA methylation data '\n", " 'from the Illumina MethylationEPIC array.\" BMC genomics 21 '\n", " '(2020): 1-13.',\n", " 'clock_name': 'cabec',\n", " 'data_type': 'methylation',\n", " 'doi': 'https://doi.org/10.1186/s12864-020-07168-8',\n", " 'notes': None,\n", " 'research_only': None,\n", " 'species': 'Homo sapiens',\n", " 'version': None,\n", " 'year': 2020}\n", "reference_values: None\n", "preprocess_name: None\n", "preprocess_dependencies: None\n", "postprocess_name: None\n", "postprocess_dependencies: None\n", "features: ['cg00000165', 'cg00001687', 'cg00004257', 'cg00012238', 'cg00015770', 'cg00018181', 'cg00039864', 'cg00053073', 'cg00071360', 'cg00074086', 'cg00112685', 'cg00116092', 'cg00156551', 'cg00172812', 'cg00193490', 'cg00199846', 'cg00231483', 'cg00260883', 'cg00262681', 'cg00265788', 'cg00290373', 'cg00314660', 'cg00347882', 'cg00370293', 'cg00381684', 'cg00387658', 'cg00397859', 'cg00406023', 'cg00448707', 'cg00456672']... [Total elements: 1892]\n", "base_model_features: None\n", "\n", "%==================================== Model Details ====================================%\n", "Model Structure:\n", "\n", "base_model: LinearModel(\n", " (linear): Linear(in_features=1892, out_features=1, bias=True)\n", ")\n", "\n", "%==================================== Model Details ====================================%\n", "Model Parameters and Weights:\n", "\n", "base_model.linear.weight: [-0.5071440935134888, 3.8805794715881348, -0.004386255983263254, -0.3082602918148041, 0.7501303553581238, -0.07783860713243484, -0.03706755116581917, -3.0622639656066895, -0.27626731991767883, -0.4478277266025543, 0.7638550400733948, 1.4799879789352417, -0.9727926254272461, -0.08195030689239502, -2.9534730911254883, 1.5299639701843262, -0.09737197309732437, 0.12180330604314804, -0.06913822144269943, -0.36189907789230347, -0.07744547724723816, -0.7775667309761047, -1.5537751913070679, -0.0737200528383255, 0.02495921030640602, -0.2793864905834198, 0.4901841878890991, 0.8282898664474487, 1.9143801927566528, -0.2619211971759796]... [Tensor of shape torch.Size([1, 1892])]\n", "base_model.linear.bias: tensor([42.8285])\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:47:39.803916Z", "iopub.status.busy": "2025-04-07T17:47:39.803816Z", "iopub.status.idle": "2025-04-07T17:47:39.808472Z", "shell.execute_reply": "2025-04-07T17:47:39.808159Z" } }, "outputs": [ { "data": { "text/plain": [ "tensor([[ 35.7819],\n", " [ 48.6824],\n", " [-73.2872],\n", " [141.0891],\n", " [ 49.2925],\n", " [-72.9852],\n", " [213.5275],\n", " [ 64.9323],\n", " [ 80.0819],\n", " [-44.4303]], 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:47:39.809924Z", "iopub.status.busy": "2025-04-07T17:47:39.809824Z", "iopub.status.idle": "2025-04-07T17:47:39.812789Z", "shell.execute_reply": "2025-04-07T17:47:39.812497Z" } }, "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:47:39.814252Z", "iopub.status.busy": "2025-04-07T17:47:39.814144Z", "iopub.status.idle": "2025-04-07T17:47:39.817492Z", "shell.execute_reply": "2025-04-07T17:47:39.817183Z" } }, "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": "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 }