{ "cells": [ { "cell_type": "markdown", "id": "2f04eee0-5928-4e74-a754-6dc2e528810c", "metadata": {}, "source": [ "# PipekElasticNet" ] }, { "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:35.543046Z", "iopub.status.busy": "2024-03-05T20:17:35.542686Z", "iopub.status.idle": "2024-03-05T20:17:36.906933Z", "shell.execute_reply": "2024-03-05T20:17:36.906611Z" } }, "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:36.908872Z", "iopub.status.busy": "2024-03-05T20:17:36.908692Z", "iopub.status.idle": "2024-03-05T20:17:36.916189Z", "shell.execute_reply": "2024-03-05T20:17:36.915931Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "class PipekElasticNet(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[mask_non_negative] + 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.PipekElasticNet)" ] }, { "cell_type": "code", "execution_count": 3, "id": "78536494-f1d9-44de-8583-c89a310d2307", "metadata": { "execution": { "iopub.execute_input": "2024-03-05T20:17:36.917755Z", "iopub.status.busy": "2024-03-05T20:17:36.917671Z", "iopub.status.idle": "2024-03-05T20:17:36.919275Z", "shell.execute_reply": "2024-03-05T20:17:36.919020Z" } }, "outputs": [], "source": [ "model = pya.models.PipekElasticNet()" ] }, { "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:36.920750Z", "iopub.status.busy": "2024-03-05T20:17:36.920670Z", "iopub.status.idle": "2024-03-05T20:17:36.922611Z", "shell.execute_reply": "2024-03-05T20:17:36.922360Z" } }, "outputs": [], "source": [ "model.metadata[\"clock_name\"] = \"pipekelasticnet\"\n", "model.metadata[\"data_type\"] = \"DNA methylation\" # Paper: DNA methylation age\n", "model.metadata[\"species\"] = \"Homo sapiens\" # Paper: human samples\n", "model.metadata[\"year\"] = 2022\n", "model.metadata[\"approved_by_author\"] = \"✅\"\n", "model.metadata[\"citation\"] = \"Pipek, Orsolya Anna, and István Csabai. \\\"A revised multi-tissue, multi-platform epigenetic clock model for methylation array data.\\\" Journal of Mathematical Chemistry 61 (2023): 376–388.\"\n", "model.metadata[\"doi\"] = \"https://doi.org/10.1007/s10910-022-01381-4\"\n", "model.metadata[\"notes\"] = \"Pan-tissue, cross-platform elastic-net chronological-age clock trained on all eligible CpGs; 239 CpGs retained non-zero coefficients.\"\n", "model.metadata[\"research_only\"] = None\n", "model.metadata[\"tissue\"] = [\"multi-tissue\"] # Paper: samples of various source tissues\n", "model.metadata[\"predicts\"] = [\"chronological age\"] # Paper: predicted DNAm age in years versus actual chronological age\n", "model.metadata[\"training_target\"] = [\"chronological age\"] # Paper: chronological age information\n", "model.metadata[\"unit\"] = [\"years\"] # Paper: chronological age (years); predicted DNAm age (years)\n", "model.metadata[\"model_type\"] = \"elastic net regression\" # Paper: elasticNet (239) was trained on all training data and resulted in 239 CpG sites with a non-zero coefficient\n", "model.metadata[\"platform\"] = [\"Illumina 27K\", \"Illumina 450K\", \"Illumina EPIC\"] # Paper: 27K, 450K and EPIC data\n", "model.metadata[\"population\"] = \"all ages\" # Paper: training data covered a broad chronological-age range\n", "model.metadata[\"journal\"] = \"Journal of Mathematical Chemistry\"\n", "model.metadata[\"last_author\"] = \"István Csabai\"\n", "model.metadata[\"n_features\"] = 239\n", "model.metadata[\"citations\"] = 2\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": "2024-03-05T20:17:36.924119Z", "iopub.status.busy": "2024-03-05T20:17:36.924044Z", "iopub.status.idle": "2024-03-05T20:17:37.181539Z", "shell.execute_reply": "2024-03-05T20:17:37.180660Z" } }, "outputs": [ { "data": { "text/plain": [ "32768" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "github_url = \"https://github.com/pipekorsi/MepiClock.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": 7, "id": "6899a4e6", "metadata": {}, "outputs": [], "source": [ "df = pd.read_csv('MepiClock/resources/model_coefficients.csv', sep=';')\n", "df['feature'] = df['probeID']\n", "df['coefficient'] = df['elasticNet (239)']\n", "df = df[df['coefficient'] != 0]\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": 8, "id": "e09b3463-4fd4-41b1-ac21-e63ddd223fe0", "metadata": { "execution": { "iopub.execute_input": "2024-03-05T20:17:37.679505Z", "iopub.status.busy": "2024-03-05T20:17:37.679254Z", "iopub.status.idle": "2024-03-05T20:17:37.682953Z", "shell.execute_reply": "2024-03-05T20:17:37.682389Z" } }, "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": 9, "id": "d7f43b99-26f2-4622-9a76-316712058877", "metadata": { "execution": { "iopub.execute_input": "2024-03-05T20:17:37.686070Z", "iopub.status.busy": "2024-03-05T20:17:37.685886Z", "iopub.status.idle": "2024-03-05T20:17:37.689293Z", "shell.execute_reply": "2024-03-05T20:17:37.688835Z" } }, "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": "markdown", "id": "f7fdae64-096a-4640-ade7-6a17b78a01d5", "metadata": {}, "source": [ "#### From CSV file" ] }, { "cell_type": "code", "execution_count": 10, "id": "86de757f-fb38-4bcb-b91e-fc3372d22aad", "metadata": { "execution": { "iopub.execute_input": "2024-03-05T20:17:37.691973Z", "iopub.status.busy": "2024-03-05T20:17:37.691810Z", "iopub.status.idle": "2024-03-05T20:17:37.713422Z", "shell.execute_reply": "2024-03-05T20:17:37.713076Z" } }, "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": 11, "id": "7a22fb20-c605-424d-8efb-7620c2c0755c", "metadata": { "execution": { "iopub.execute_input": "2024-03-05T20:17:37.715600Z", "iopub.status.busy": "2024-03-05T20:17:37.715468Z", "iopub.status.idle": "2024-03-05T20:17:37.717220Z", "shell.execute_reply": "2024-03-05T20:17:37.716911Z" } }, "outputs": [], "source": [ "model.preprocess_name = None\n", "model.preprocess_dependencies = None" ] }, { "cell_type": "code", "execution_count": 12, "id": "ff4a21cb-cf41-44dc-9ed1-95cf8aa15772", "metadata": { "execution": { "iopub.execute_input": "2024-03-05T20:17:37.719024Z", "iopub.status.busy": "2024-03-05T20:17:37.718901Z", "iopub.status.idle": "2024-03-05T20:17:37.720622Z", "shell.execute_reply": "2024-03-05T20:17:37.720306Z" } }, "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": 13, "id": "2168355c-47d9-475d-b816-49f65e74887c", "metadata": { "execution": { "iopub.execute_input": "2024-03-05T20:17:37.722338Z", "iopub.status.busy": "2024-03-05T20:17:37.722225Z", "iopub.status.idle": "2024-03-05T20:17:37.725744Z", "shell.execute_reply": "2024-03-05T20:17:37.725443Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "%==================================== Model Details ====================================%\n", "Model Attributes:\n", "\n", "training: True\n", "metadata: {'approved_by_author': '✅',\n", " 'citation': 'Pipek, Orsolya Anna, and István Csabai. \"A revised multi-tissue, '\n", " 'multi-platform epigenetic clock model for methylation array '\n", " 'data.\" Journal of Mathematical Chemistry 61.2 (2023): 376-388.',\n", " 'clock_name': 'pipekelasticnet',\n", " 'data_type': 'methylation',\n", " 'doi': 'https://doi.org/10.1007/s10910-022-01381-4',\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: 'anti_log_linear'\n", "postprocess_dependencies: None\n", "features: ['cg00027083', 'cg00059225', 'cg00075967', 'cg00168942', 'cg00290506', 'cg00343092', 'cg00528967', 'cg00651216', 'cg00812502', 'cg00864867', 'cg01222684', 'cg01262913', 'cg01294695', 'cg01353448', 'cg01407797', 'cg01459453', 'cg01485645', 'cg01507173', 'cg01511567', 'cg01570885', 'cg01580568', 'cg01580888', 'cg01860753', 'cg01968793', 'cg01994328', 'cg02217159', 'cg02275294', 'cg02332492', 'cg02335441', 'cg02388150']... [Total elements: 239]\n", "base_model_features: None\n", "\n", "%==================================== Model Details ====================================%\n", "Model Structure:\n", "\n", "base_model: LinearModel(\n", " (linear): Linear(in_features=239, out_features=1, bias=True)\n", ")\n", "\n", "%==================================== Model Details ====================================%\n", "Model Parameters and Weights:\n", "\n", "base_model.linear.weight: [0.1439734548330307, 1.4801537990570068, 0.03225376456975937, -0.0058419122360646725, -0.9698857665061951, -0.02445327118039131, -0.25678759813308716, -0.1429552286863327, -0.45733991265296936, 0.03336525335907936, 0.06893794238567352, -0.016240336000919342, -0.028347602114081383, 0.08623908460140228, -0.006927416194230318, -0.4072648584842682, -0.11168642342090607, 0.0335581935942173, -1.1504876613616943, -0.18203186988830566, 0.06303419172763824, 0.7362451553344727, -0.01122856605798006, -0.1645817756652832, -0.3766438066959381, -0.22185027599334717, -0.14580827951431274, 0.11524636298418045, -0.07323136180639267, 0.19775758683681488]... [Tensor of shape torch.Size([1, 239])]\n", "base_model.linear.bias: tensor([0.3361])\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": 14, "id": "936b9877-d076-4ced-99aa-e8d4c58c5caf", "metadata": { "execution": { "iopub.execute_input": "2024-03-05T20:17:37.727432Z", "iopub.status.busy": "2024-03-05T20:17:37.727339Z", "iopub.status.idle": "2024-03-05T20:17:37.731216Z", "shell.execute_reply": "2024-03-05T20:17:37.730942Z" } }, "outputs": [ { "data": { "text/plain": [ "tensor([[ 26.4756],\n", " [ 69.0214],\n", " [ -0.9994],\n", " [ -0.9954],\n", " [ 9.0836],\n", " [204.6643],\n", " [146.1240],\n", " [ -0.9388],\n", " [ 94.5212],\n", " [ 54.5029]], dtype=torch.float64, grad_fn=)" ] }, "execution_count": 14, "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": 15, "id": "5ef2fa8d-c80b-4fdd-8555-79c0d541788e", "metadata": { "execution": { "iopub.execute_input": "2024-03-05T20:17:37.732855Z", "iopub.status.busy": "2024-03-05T20:17:37.732762Z", "iopub.status.idle": "2024-03-05T20:17:37.735692Z", "shell.execute_reply": "2024-03-05T20:17:37.735426Z" } }, "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": 16, "id": "11aeaa70-44c0-42f9-86d7-740e3849a7a6", "metadata": { "execution": { "iopub.execute_input": "2024-03-05T20:17:37.737247Z", "iopub.status.busy": "2024-03-05T20:17:37.737152Z", "iopub.status.idle": "2024-03-05T20:17:37.740189Z", "shell.execute_reply": "2024-03-05T20:17:37.739959Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Deleted file: reference_feature_values.csv\n", "Deleted folder: MepiClock\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 }