{ "cells": [ { "cell_type": "markdown", "id": "2f04eee0-5928-4e74-a754-6dc2e528810c", "metadata": {}, "source": [ "# StocZ" ] }, { "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": {}, "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": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "class StocZ(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.StocZ)" ] }, { "cell_type": "code", "execution_count": 3, "id": "78536494-f1d9-44de-8583-c89a310d2307", "metadata": {}, "outputs": [], "source": [ "model = pya.models.StocZ()" ] }, { "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": {}, "outputs": [], "source": [ "model.metadata[\"clock_name\"] = \"stocz\"\n", "model.metadata[\"data_type\"] = \"DNA methylation\" # Paper: DNA methylation clocks\n", "model.metadata[\"species\"] = \"Homo sapiens\" # Paper: human cohort\n", "model.metadata[\"year\"] = 2024\n", "model.metadata[\"approved_by_author\"] = \"✅\"\n", "model.metadata[\"citation\"] = \"Tong, Huige, et al. \\\"Quantifying the stochastic component of epigenetic aging.\\\" Nature Aging 4 (2024): 886–901.\"\n", "model.metadata[\"doi\"] = \"https://doi.org/10.1038/s43587-024-00600-8\"\n", "model.metadata[\"notes\"] = \"Stochastic chronological-age clock built from simulated methylation trajectories at Zhang clock CpGs; it is a stochastic counterpart, not the original Zhang clock.\"\n", "model.metadata[\"research_only\"] = None\n", "model.metadata[\"tissue\"] = [\"sorted monocytes\"] # Paper: Illumina 450k DNAm data of sorted monocyte samples from 1,202 donors\n", "model.metadata[\"predicts\"] = [\"chronological age\"] # Paper: machine learning predictors of chronological age\n", "model.metadata[\"training_target\"] = [\"chronological age\"] # Paper: artificial cohorts from which machine learning predictor of age can be derived\n", "model.metadata[\"unit\"] = [\"years\"] # Paper: estimate DNAm-Age\n", "model.metadata[\"model_type\"] = \"elastic net regression\" # Paper: elastic-net regression\n", "model.metadata[\"platform\"] = [\"Illumina 450K\"] # Paper: Illumina 450k DNAm data of sorted monocyte samples\n", "model.metadata[\"population\"] = \"adults\" # Paper: MESA monocytes: minimum age 44 years, maximum age 83 years\n", "model.metadata[\"journal\"] = \"Nature Aging\"\n", "model.metadata[\"last_author\"] = \"Andrew E. Teschendorff\"\n", "model.metadata[\"n_features\"] = 514\n", "model.metadata[\"citations\"] = 66\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": "192924bd-8553-4840-85e9-3ea02b024b79", "metadata": {}, "source": [ "#### Download directly with curl" ] }, { "cell_type": "code", "execution_count": 5, "id": "6675770e-a5d1-40ab-93e1-775f288fed1c", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "supplementary_url = \"https://figshare.com/ndownloader/files/42406308\"\n", "supplementary_file_name = \"glmStocAll.Rd\"\n", "os.system(f\"curl -L -o {supplementary_file_name} {supplementary_url}\")" ] }, { "cell_type": "markdown", "id": "aeee6c5a-4e0a-4f2a-acef-d657596f453a", "metadata": {}, "source": [ "#### Download from R package" ] }, { "cell_type": "code", "execution_count": 6, "id": "d81f2c9d-362f-43cb-ad52-012e28217164", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Writing download.r\n" ] } ], "source": [ "%%writefile download.r\n", "\n", "options(repos = c(CRAN = \"https://cloud.r-project.org/\"))\n", "\n", "# Function to extract and save coefficients and intercepts\n", "ExtractCoefficients <- function(){\n", " load(\"glmStocALL.Rd\") # Load in stochastic clock information\n", "\n", " # Check the loaded object structure\n", " if (!exists(\"glmStocALL.lo\")) {\n", " stop(\"The object glmStocALL.lo was not found in the loaded .Rd file.\")\n", " }\n", "\n", " # List to store coefficients and intercepts for each clock\n", " coefficients_list <- list()\n", "\n", " for (c in 1:length(glmStocALL.lo)) {\n", " glm.o <- glmStocALL.lo[[c]]\n", "\n", " # Ensure glm.o is a glmnet object\n", " if (!inherits(glm.o, \"glmnet\")) {\n", " warning(paste(\"Object at index\", c, \"is not a glmnet object. Skipping.\"))\n", " next\n", " }\n", "\n", " # Extract the coefficients and intercept from the final iteration\n", " intercept <- glm.o$a0[length(glm.o$a0)]\n", " coefficients <- as.matrix(glm.o$beta)[, length(glm.o$lambda)]\n", "\n", " print(length(coefficients))\n", " print(length(rownames(coefficients)))\n", "\n", " # Create a data frame with feature names and coefficients\n", " coef_df <- data.frame(\n", " Feature = rownames(as.matrix(glm.o$beta)),\n", " Coefficient = as.numeric(coefficients),\n", " Intercept = rep(intercept, length(coefficients))\n", " )\n", " \n", " # Save each clock's coefficients to a CSV file\n", " write.csv(coef_df, file = paste0(\"Coefficients_Clock_\", c, \".csv\"), row.names = FALSE)\n", " \n", " # Append to the list\n", " coefficients_list[[c]] <- coef_df\n", " }\n", "\n", " return(coefficients_list) # Return the list for further inspection if needed\n", "}\n", "\n", "# Run the function\n", "coefficients_list <- ExtractCoefficients()" ] }, { "cell_type": "code", "execution_count": 7, "id": "1ce2bac8-dd33-46cb-a7b6-14a1d0976f05", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "os.system(\"Rscript download.r\")" ] }, { "cell_type": "markdown", "id": "84930b94-fff8-4e1f-85ef-2194e8a8ee4f", "metadata": {}, "source": [ "## Load features" ] }, { "cell_type": "markdown", "id": "dbb77f97-01d4-4c63-aa40-ee24de8bc0e9", "metadata": {}, "source": [ "#### From CSV file" ] }, { "cell_type": "code", "execution_count": 8, "id": "110a5ded-d25f-4cef-8e84-4f51210dfc26", "metadata": {}, "outputs": [], "source": [ "df = pd.read_csv('Coefficients_Clock_2.csv')\n", "df['feature'] = df['Feature']\n", "df['coefficient'] = df['Coefficient']\n", "model.features = df['feature'].tolist()" ] }, { "cell_type": "markdown", "id": "f81dd175-8773-47da-864a-643f45195bf2", "metadata": {}, "source": [ "## Load weights into base model" ] }, { "cell_type": "code", "execution_count": 9, "id": "e09b3463-4fd4-41b1-ac21-e63ddd223fe0", "metadata": {}, "outputs": [], "source": [ "weights = torch.tensor(df['coefficient'].tolist()).unsqueeze(0)\n", "intercept = torch.tensor([df['Intercept'][0]])" ] }, { "cell_type": "markdown", "id": "3bbfeba6-07a3-49c6-b56a-0b9c1c882167", "metadata": {}, "source": [ "#### Linear model" ] }, { "cell_type": "code", "execution_count": 10, "id": "d7f43b99-26f2-4622-9a76-316712058877", "metadata": {}, "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": "b43d29e6-ec61-450c-be21-989ad9eaebb4", "metadata": {}, "source": [ "## Load reference values" ] }, { "cell_type": "code", "execution_count": 11, "id": "ade0f4c9-2298-4fc3-bb72-d200907dd731", "metadata": {}, "outputs": [], "source": [ "model.reference_values = None" ] }, { "cell_type": "markdown", "id": "b42caeae-f255-45aa-9f00-3bed6ef7d26f", "metadata": {}, "source": [ "## Load preprocess and postprocess objects" ] }, { "cell_type": "code", "execution_count": 12, "id": "7a22fb20-c605-424d-8efb-7620c2c0755c", "metadata": {}, "outputs": [], "source": [ "model.preprocess_name = None\n", "model.preprocess_dependencies = None" ] }, { "cell_type": "code", "execution_count": 13, "id": "ff4a21cb-cf41-44dc-9ed1-95cf8aa15772", "metadata": {}, "outputs": [], "source": [ "model.postprocess_name = None\n", "model.postprocess_dependencies = None" ] }, { "cell_type": "markdown", "id": "2466d7e7-5f1e-4d4a-81f4-721e56958378", "metadata": {}, "source": [ "## Check all clock parameters" ] }, { "cell_type": "code", "execution_count": 14, "id": "2168355c-47d9-475d-b816-49f65e74887c", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "%==================================== Model Details ====================================%\n", "Model Attributes:\n", "\n", "training: True\n", "metadata: {'approved_by_author': '✅',\n", " 'citation': 'Tong, Huige, et al. \"Quantifying the stochastic component of '\n", " 'epigenetic aging.\" Nature Aging (2024): 1-16.',\n", " 'clock_name': 'stocz',\n", " 'data_type': 'methylation',\n", " 'doi': 'https://doi.org/10.1038/s43587-024-00600-8',\n", " 'notes': None,\n", " 'research_only': None,\n", " 'species': 'Homo sapiens',\n", " 'version': None,\n", " 'year': 2024}\n", "reference_values: None\n", "preprocess_name: None\n", "preprocess_dependencies: None\n", "postprocess_name: None\n", "postprocess_dependencies: None\n", "features: ['cg24611351', 'cg24173182', 'cg09604333', 'cg13617776', 'cg09432590', 'cg05516505', 'cg12757684', 'cg23606718', 'cg20050761', 'cg22452230', 'cg05898618', 'cg01620164', 'cg06758350', 'cg23615741', 'cg09692396', 'cg02046143', 'cg08540945', 'cg11714320', 'cg22708738', 'cg21567504', 'cg08313880', 'cg03527802', 'cg23995914', 'cg04027548', 'cg07077459', 'cg03025830', 'cg07978099', 'cg24349631', 'cg04218760', 'cg24788483']... [Total elements: 514]\n", "base_model_features: None\n", "\n", "%==================================== Model Details ====================================%\n", "Model Structure:\n", "\n", "base_model: LinearModel(\n", " (linear): Linear(in_features=514, out_features=1, bias=True)\n", ")\n", "\n", "%==================================== Model Details ====================================%\n", "Model Parameters and Weights:\n", "\n", "base_model.linear.weight: [-3.350179433822632, -0.036642078310251236, -0.05118434131145477, 0.13607171177864075, -0.6929044127464294, -8.596583366394043, -0.023057660087943077, 22.69631576538086, 0.00651215435937047, -1.4592914581298828, -0.09501103311777115, -0.12129057198762894, -0.08514729142189026, -0.0008293375140056014, 0.4517977833747864, -0.3498646914958954, 15.742756843566895, -0.005218011327087879, -0.37894847989082336, -0.02003936469554901, 0.29712849855422974, -0.18342454731464386, -0.31919535994529724, -2.756777286529541, -2.310011625289917, 0.009594087488949299, 0.0197058767080307, 0.18678680062294006, 0.004259498789906502, -3.520700216293335]... [Tensor of shape torch.Size([1, 514])]\n", "base_model.linear.bias: tensor([64.8077])\n", "\n", "%==================================== Model Details ====================================%\n", "\n" ] } ], "source": [ "pya.utils.print_model_details(model)" ] }, { "cell_type": "markdown", "id": "78e2387c-6de1-4073-b4a5-b8b8e430abdb", "metadata": {}, "source": [ "## Basic test" ] }, { "cell_type": "code", "execution_count": 15, "id": "936b9877-d076-4ced-99aa-e8d4c58c5caf", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "tensor([[ -65.2707],\n", " [-228.6931],\n", " [ 81.9692],\n", " [ 186.4775],\n", " [ -30.6134],\n", " [ 20.5118],\n", " [ 50.0692],\n", " [ 127.1051],\n", " [ 150.1440],\n", " [ -14.1187]], dtype=torch.float64, grad_fn=)" ] }, "execution_count": 15, "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": "75642087-b880-429b-b19b-c1eaea33614f", "metadata": {}, "source": [ "## Save torch model" ] }, { "cell_type": "code", "execution_count": 16, "id": "5ef2fa8d-c80b-4fdd-8555-79c0d541788e", "metadata": {}, "outputs": [], "source": [ "torch.save(model, f\"../weights/{model.metadata['clock_name']}.pt\")" ] }, { "cell_type": "markdown", "id": "f65d9bb5-5baa-486b-bf25-f68f542bd5b7", "metadata": {}, "source": [ "## Clear directory\n", "" ] }, { "cell_type": "code", "execution_count": 17, "id": "11aeaa70-44c0-42f9-86d7-740e3849a7a6", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Deleted file: glmStocAll.Rd\n", "Deleted file: download.r\n", "Deleted folder: .ipynb_checkpoints\n", "Deleted file: Coefficients_Clock_3.csv\n", "Deleted file: Coefficients_Clock_2.csv\n", "Deleted file: Coefficients_Clock_1.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": "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 }