{ "cells": [ { "cell_type": "markdown", "id": "2f04eee0-5928-4e74-a754-6dc2e528810c", "metadata": {}, "source": [ "# Thompson" ] }, { "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:23:50.590960Z", "iopub.status.busy": "2024-03-05T21:23:50.590526Z", "iopub.status.idle": "2024-03-05T21:23:51.909586Z", "shell.execute_reply": "2024-03-05T21:23:51.909287Z" } }, "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:51.911447Z", "iopub.status.busy": "2024-03-05T21:23:51.911275Z", "iopub.status.idle": "2024-03-05T21:23:51.920416Z", "shell.execute_reply": "2024-03-05T21:23:51.920153Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "class Thompson(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.Thompson)" ] }, { "cell_type": "code", "execution_count": 3, "id": "78536494-f1d9-44de-8583-c89a310d2307", "metadata": { "execution": { "iopub.execute_input": "2024-03-05T21:23:51.921838Z", "iopub.status.busy": "2024-03-05T21:23:51.921758Z", "iopub.status.idle": "2024-03-05T21:23:51.923419Z", "shell.execute_reply": "2024-03-05T21:23:51.923202Z" } }, "outputs": [], "source": [ "model = pya.models.Thompson()" ] }, { "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:51.924881Z", "iopub.status.busy": "2024-03-05T21:23:51.924805Z", "iopub.status.idle": "2024-03-05T21:23:51.926695Z", "shell.execute_reply": "2024-03-05T21:23:51.926466Z" } }, "outputs": [], "source": [ "model.metadata[\"clock_name\"] = \"thompson\"\n", "model.metadata[\"data_type\"] = \"DNA methylation\" # Paper: The clocks use mouse CpG DNA-methylation frequencies.\n", "model.metadata[\"species\"] = \"Mus musculus\" # Paper: The study develops full-lifespan epigenetic clocks for mice.\n", "model.metadata[\"year\"] = 2018\n", "model.metadata[\"approved_by_author\"] = \"✅\"\n", "model.metadata[\"citation\"] = \"Thompson, M. J., Chwiałkowska, K., Rubbi, L. et al. A multi-tissue full lifespan epigenetic clock for mice. Aging (Albany NY) 10, 2832–2854 (2018).\"\n", "model.metadata[\"doi\"] = \"https://doi.org/10.18632/aging.101590\"\n", "model.metadata[\"notes\"] = \"Full-lifespan multi-tissue mouse DNA-methylation clock fit by elastic net to RRBS CpG methylation across 1,147 samples from ten tissues and multiple strains; the 582-site all-CpG model estimates chronological age and detects intervention- and genotype-associated age acceleration.\"\n", "model.metadata[\"research_only\"] = None\n", "model.metadata[\"tissue\"] = [\"adipose tissue\", \"blood\", \"cerebellum\", \"brain cortex\", \"heart\", \"kidney\", \"liver\", \"lung\", \"skeletal muscle\", \"spleen\"] # Paper: Table 2 lists adipose, blood, kidney, liver, lung, muscle, cortex, heart, cerebellum, and spleen datasets.\n", "model.metadata[\"predicts\"] = [\"chronological age\"] # Paper: The clock estimates chronological age at DNA sample collection.\n", "model.metadata[\"training_target\"] = [\"chronological age\"] # Paper: Penalized regression predicts sample chronological age in months from CpG methylation.\n", "model.metadata[\"unit\"] = [\"months\"] # Paper: Age errors and predictions are reported in months, and the released workflow returns predicted age in months.\n", "model.metadata[\"model_type\"] = \"elastic net regression\" # Paper: The all-CpG clock uses elastic net with alpha equal to 0.5.\n", "model.metadata[\"platform\"] = [\"RRBS\"] # Paper: Methylation was measured with reduced-representation bisulfite sequencing.\n", "model.metadata[\"population\"] = \"mice\" # Paper: The combined datasets span prenatal age through 32.2 months and include C57BL/6, BALB/c, Diversity Outbred, dwarf, GHRKO, and HMDP strains.\n", "model.metadata[\"journal\"] = \"Aging (Albany NY)\"\n", "model.metadata[\"last_author\"] = \"Matteo Pellegrini\"\n", "model.metadata[\"n_features\"] = 582\n", "model.metadata[\"citations\"] = 236\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": "08180e89-7f9b-4c12-ae7d-057c2e27effa", "metadata": {}, "source": [ "#### Download GitHub repository" ] }, { "cell_type": "code", "execution_count": 5, "id": "a57b7849-9210-43d0-9c47-db7b524f6858", "metadata": { "execution": { "iopub.execute_input": "2024-03-05T21:23:51.928212Z", "iopub.status.busy": "2024-03-05T21:23:51.928139Z", "iopub.status.idle": "2024-03-05T21:23:52.918934Z", "shell.execute_reply": "2024-03-05T21:23:52.918386Z" } }, "outputs": [ { "data": { "text/plain": [ "0" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "github_url = \"https://github.com/kerepesi/MouseAgingClocks.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": "8a3d5de6-6303-487a-8b4d-e6345792f7be", "metadata": { "execution": { "iopub.execute_input": "2024-03-05T21:23:52.922018Z", "iopub.status.busy": "2024-03-05T21:23:52.921828Z", "iopub.status.idle": "2024-03-05T21:23:52.929443Z", "shell.execute_reply": "2024-03-05T21:23:52.929039Z" } }, "outputs": [], "source": [ "df = pd.read_table('MouseAgingClocks/ClockData/Thompson2018-ElasticNet_aging_clock.txt', skiprows=1)\n", "intercept = df['Coefficient'].iloc[0]\n", "df = df[1:]\n", "df['feature'] = df['Chromosome'].astype(str) + ':' + df['Coordinate'].astype(int).astype(str)\n", "df['coefficient'] = df['Coefficient']\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": "2024-03-05T21:23:52.931889Z", "iopub.status.busy": "2024-03-05T21:23:52.931727Z", "iopub.status.idle": "2024-03-05T21:23:52.934651Z", "shell.execute_reply": "2024-03-05T21:23:52.934242Z" } }, "outputs": [], "source": [ "weights = torch.tensor(df['coefficient'].tolist()).unsqueeze(0)\n", "intercept = torch.tensor([intercept])" ] }, { "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:52.936972Z", "iopub.status.busy": "2024-03-05T21:23:52.936810Z", "iopub.status.idle": "2024-03-05T21:23:52.939876Z", "shell.execute_reply": "2024-03-05T21:23:52.939516Z" } }, "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:52.941971Z", "iopub.status.busy": "2024-03-05T21:23:52.941853Z", "iopub.status.idle": "2024-03-05T21:23:52.943777Z", "shell.execute_reply": "2024-03-05T21:23:52.943425Z" } }, "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:52.945749Z", "iopub.status.busy": "2024-03-05T21:23:52.945651Z", "iopub.status.idle": "2024-03-05T21:23:52.947449Z", "shell.execute_reply": "2024-03-05T21:23:52.947120Z" } }, "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:52.949165Z", "iopub.status.busy": "2024-03-05T21:23:52.949056Z", "iopub.status.idle": "2024-03-05T21:23:52.950882Z", "shell.execute_reply": "2024-03-05T21:23:52.950561Z" } }, "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-05T21:23:52.952698Z", "iopub.status.busy": "2024-03-05T21:23:52.952598Z", "iopub.status.idle": "2024-03-05T21:23:52.956062Z", "shell.execute_reply": "2024-03-05T21:23:52.955790Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "%==================================== Model Details ====================================%\n", "Model Attributes:\n", "\n", "training: True\n", "metadata: {'approved_by_author': '✅',\n", " 'citation': 'Thompson, Michael J., et al. \"A multi-tissue full lifespan '\n", " 'epigenetic clock for mice.\" Aging (Albany NY) 10.10 (2018): '\n", " '2832.',\n", " 'clock_name': 'thompson',\n", " 'data_type': 'methylation',\n", " 'doi': 'https://doi.org/10.18632/aging.101590',\n", " 'notes': None,\n", " 'research_only': None,\n", " 'species': 'Mus musculus',\n", " 'version': None,\n", " 'year': 2018}\n", "reference_values: None\n", "preprocess_name: None\n", "preprocess_dependencies: None\n", "postprocess_name: None\n", "postprocess_dependencies: None\n", "features: ['chr1:9967422', 'chr1:9967428', 'chr1:13126576', 'chr1:15286937', 'chr1:46800385', 'chr1:55087536', 'chr1:63273286', 'chr1:63273288', 'chr1:64690282', 'chr1:71603645', 'chr1:79761546', 'chr1:79858375', 'chr1:84695279', 'chr1:84934769', 'chr1:89455649', 'chr1:92848744', 'chr1:92848748', 'chr1:95666316', 'chr1:103479589', 'chr1:105270925', 'chr1:106758726', 'chr1:118310888', 'chr1:118311288', 'chr1:119648512', 'chr1:120602265', 'chr1:120602331', 'chr1:128359556', 'chr1:132331689', 'chr1:132937328', 'chr1:135374481']... [Total elements: 582]\n", "base_model_features: None\n", "\n", "%==================================== Model Details ====================================%\n", "Model Structure:\n", "\n", "base_model: LinearModel(\n", " (linear): Linear(in_features=582, out_features=1, bias=True)\n", ")\n", "\n", "%==================================== Model Details ====================================%\n", "Model Parameters and Weights:\n", "\n", "base_model.linear.weight: [0.7605000138282776, 0.12610000371932983, 4.3765997886657715, 5.6855998039245605, -0.5194000005722046, -0.6355000138282776, 0.41659998893737793, 1.2926000356674194, 5.576700210571289, -0.9544000029563904, -5.0493998527526855, -0.2711000144481659, 0.24879999458789825, -0.8901000022888184, 0.7444000244140625, 0.03920000046491623, 0.40560001134872437, -2.0560998916625977, 0.5519000291824341, -0.663100004196167, -0.8413000106811523, -3.921999931335449, -3.1031999588012695, -1.9629000425338745, 2.824700117111206, -0.3255000114440918, 1.7187999486923218, -1.5643999576568604, -0.7063000202178955, -2.196000099182129]... [Tensor of shape torch.Size([1, 582])]\n", "base_model.linear.bias: tensor([30.3172])\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:52.957798Z", "iopub.status.busy": "2024-03-05T21:23:52.957702Z", "iopub.status.idle": "2024-03-05T21:23:52.961506Z", "shell.execute_reply": "2024-03-05T21:23:52.961222Z" } }, "outputs": [ { "data": { "text/plain": [ "tensor([[102.1936],\n", " [ 83.5008],\n", " [ 61.2582],\n", " [-60.8014],\n", " [-27.0123],\n", " [ 77.8211],\n", " [ 51.7655],\n", " [ 57.8975],\n", " [167.7028],\n", " [ 52.8332]], 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:52.963133Z", "iopub.status.busy": "2024-03-05T21:23:52.963039Z", "iopub.status.idle": "2024-03-05T21:23:52.966262Z", "shell.execute_reply": "2024-03-05T21:23:52.965996Z" } }, "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:52.967858Z", "iopub.status.busy": "2024-03-05T21:23:52.967773Z", "iopub.status.idle": "2024-03-05T21:23:52.973752Z", "shell.execute_reply": "2024-03-05T21:23:52.973497Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Deleted folder: MouseAgingClocks\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 }