{ "cells": [ { "cell_type": "markdown", "id": "810b3f5e", "metadata": {}, "source": [ "# EPICGA" ] }, { "cell_type": "markdown", "id": "510d6245", "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": "b58e42f2", "metadata": {}, "source": [ "Let's first import some packages:" ] }, { "cell_type": "code", "execution_count": 1, "id": "36802d76", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T20:24:55.568991Z", "iopub.status.busy": "2026-07-04T20:24:55.568771Z", "iopub.status.idle": "2026-07-04T20:24:58.572759Z", "shell.execute_reply": "2026-07-04T20:24:58.572263Z" } }, "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": "c8d0d60d", "metadata": {}, "source": [ "## Instantiate model class" ] }, { "cell_type": "code", "execution_count": 2, "id": "95f20ea5", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T20:24:58.574434Z", "iopub.status.busy": "2026-07-04T20:24:58.574265Z", "iopub.status.idle": "2026-07-04T20:24:58.576916Z", "shell.execute_reply": "2026-07-04T20:24:58.576531Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "class EPICGA(LinearReferenceClock):\n", " def postprocess(self, x):\n", " \"\"\"Model returns gestational age in days; convert to weeks.\"\"\"\n", " return x / 7.0\n", "\n" ] } ], "source": [ "def print_entire_class(cls):\n", " source = inspect.getsource(cls)\n", " print(source)\n", "\n", "print_entire_class(pya.models.EPICGA)" ] }, { "cell_type": "code", "execution_count": 3, "id": "6b7c3e02", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T20:24:58.578056Z", "iopub.status.busy": "2026-07-04T20:24:58.577976Z", "iopub.status.idle": "2026-07-04T20:24:58.579590Z", "shell.execute_reply": "2026-07-04T20:24:58.579099Z" } }, "outputs": [], "source": [ "model = pya.models.EPICGA()" ] }, { "cell_type": "markdown", "id": "7b6c0d1a", "metadata": {}, "source": [ "## Define clock metadata" ] }, { "cell_type": "code", "execution_count": 4, "id": "2b547148", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T20:24:58.580834Z", "iopub.status.busy": "2026-07-04T20:24:58.580742Z", "iopub.status.idle": "2026-07-04T20:24:58.583147Z", "shell.execute_reply": "2026-07-04T20:24:58.582657Z" } }, "outputs": [], "source": [ "model.metadata[\"clock_name\"] = \"epicga\"\n", "model.metadata[\"data_type\"] = \"DNA methylation\" # Paper: An EPIC DNA-methylation predictor of gestational age.\n", "model.metadata[\"species\"] = \"Homo sapiens\" # Paper: An EPIC DNA-methylation predictor of gestational age.\n", "model.metadata[\"year\"] = 2021\n", "model.metadata[\"approved_by_author\"] = \"⌛\"\n", "model.metadata[\"citation\"] = \"Haftorn, K. L. et al. An EPIC predictor of gestational age and its application to newborns conceived by assisted reproductive technologies. Clinical Epigenetics 13, 82 (2021).\"\n", "model.metadata[\"doi\"] = \"https://doi.org/10.1186/s13148-021-01055-z\"\n", "model.metadata[\"notes\"] = \"LASSO predictor of ultrasound-estimated gestational age in days from umbilical cord-blood DNA methylation, trained in 755 non-ART START newborns.\"\n", "model.metadata[\"research_only\"] = None\n", "model.metadata[\"tissue\"] = [\"cord blood\"] # Paper: Cord blood samples were taken immediately after birth.\n", "model.metadata[\"predicts\"] = [\"gestational age\"] # Paper: An EPIC DNA-methylation predictor of gestational age.\n", "model.metadata[\"training_target\"] = [\"gestational age\"] # Paper: Clinically estimated gestational age was regressed on CpGs.\n", "model.metadata[\"unit\"] = [\"days\"] # Paper: Intercept 293.4557 and coefficients reproduce gestational age in days.\n", "model.metadata[\"model_type\"] = \"LASSO regression\" # Paper: Lasso regression selected 176 CpGs.\n", "model.metadata[\"platform\"] = [\"Illumina EPIC\"] # Paper: An EPIC DNA-methylation predictor of gestational age.\n", "model.metadata[\"population\"] = \"newborns\" # Paper: The clock was trained on 755 non-ART newborns from START.\n", "model.metadata[\"journal\"] = \"Clinical Epigenetics\"\n", "model.metadata[\"last_author\"] = \"Jon Bohlin\"\n", "model.metadata[\"n_features\"] = 176\n", "model.metadata[\"citations\"] = 54\n", "model.metadata[\"citations_date\"] = \"2026-07-05\"\n" ] }, { "cell_type": "markdown", "id": "46a068ec", "metadata": {}, "source": [ "## Download clock dependencies" ] }, { "cell_type": "code", "execution_count": 5, "id": "49f837fb", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T20:24:58.584590Z", "iopub.status.busy": "2026-07-04T20:24:58.584487Z", "iopub.status.idle": "2026-07-04T20:24:58.847372Z", "shell.execute_reply": "2026-07-04T20:24:58.845659Z" } }, "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%2Fs13148-021-01055-z/MediaObjects/13148_2021_1055_MOESM7_ESM.csv\"\n", "supplementary_file_name = \"epic_ga_coefs.csv\"\n", "os.system(f\"curl -sL -o {supplementary_file_name} {supplementary_url}\")" ] }, { "cell_type": "markdown", "id": "208f2bfe", "metadata": {}, "source": [ "## Load features" ] }, { "cell_type": "code", "execution_count": 6, "id": "b7bcb893", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T20:24:58.850865Z", "iopub.status.busy": "2026-07-04T20:24:58.850575Z", "iopub.status.idle": "2026-07-04T20:24:58.865186Z", "shell.execute_reply": "2026-07-04T20:24:58.864499Z" } }, "outputs": [], "source": [ "df = pd.read_csv('epic_ga_coefs.csv')\n", "mask = df['cpgs'].astype(str).str.lower().isin(['intercept', '(intercept)'])\n", "intercept_value = float(df.loc[mask, 's0'].iloc[0]) if mask.any() else 0.0\n", "coef_df = df.loc[~mask].reset_index(drop=True)\n", "model.features = coef_df['cpgs'].tolist()" ] }, { "cell_type": "markdown", "id": "783c47e0", "metadata": {}, "source": [ "## Load weights into base model" ] }, { "cell_type": "code", "execution_count": 7, "id": "c1fc937c", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T20:24:58.866831Z", "iopub.status.busy": "2026-07-04T20:24:58.866686Z", "iopub.status.idle": "2026-07-04T20:24:58.872418Z", "shell.execute_reply": "2026-07-04T20:24:58.872012Z" } }, "outputs": [], "source": [ "weights = torch.tensor(coef_df['s0'].tolist()).unsqueeze(0).float()\n", "intercept = torch.tensor([intercept_value]).float()" ] }, { "cell_type": "code", "execution_count": 8, "id": "2877d12c", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T20:24:58.873915Z", "iopub.status.busy": "2026-07-04T20:24:58.873831Z", "iopub.status.idle": "2026-07-04T20:24:58.879196Z", "shell.execute_reply": "2026-07-04T20:24:58.878756Z" } }, "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": "167840d2", "metadata": {}, "source": [ "## Load reference values" ] }, { "cell_type": "code", "execution_count": 9, "id": "a1446f13", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T20:24:58.881152Z", "iopub.status.busy": "2026-07-04T20:24:58.881012Z", "iopub.status.idle": "2026-07-04T20:24:58.883082Z", "shell.execute_reply": "2026-07-04T20:24:58.882563Z" } }, "outputs": [], "source": [ "model.reference_values = None" ] }, { "cell_type": "markdown", "id": "f8c7fca0", "metadata": {}, "source": [ "## Load preprocess and postprocess objects" ] }, { "cell_type": "code", "execution_count": 10, "id": "e1811c4c", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T20:24:58.884651Z", "iopub.status.busy": "2026-07-04T20:24:58.884530Z", "iopub.status.idle": "2026-07-04T20:24:58.886392Z", "shell.execute_reply": "2026-07-04T20:24:58.885944Z" } }, "outputs": [], "source": [ "model.preprocess_name = None\n", "model.preprocess_dependencies = None" ] }, { "cell_type": "code", "execution_count": 11, "id": "81acef67", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T20:24:58.887594Z", "iopub.status.busy": "2026-07-04T20:24:58.887507Z", "iopub.status.idle": "2026-07-04T20:24:58.889336Z", "shell.execute_reply": "2026-07-04T20:24:58.888870Z" } }, "outputs": [], "source": [ "model.postprocess_name = 'days_to_weeks'\n", "model.postprocess_dependencies = None" ] }, { "cell_type": "markdown", "id": "36789dee", "metadata": {}, "source": [ "## Check all clock parameters" ] }, { "cell_type": "code", "execution_count": 12, "id": "6bf7b63e", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T20:24:58.890523Z", "iopub.status.busy": "2026-07-04T20:24:58.890437Z", "iopub.status.idle": "2026-07-04T20:24:58.909113Z", "shell.execute_reply": "2026-07-04T20:24:58.908664Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "%==================================== Model Details ====================================%\n", "Model Attributes:\n", "\n", "training: True\n", "metadata: {'approved_by_author': '⌛',\n", " 'citation': 'Haftorn, Kristine L., et al. \"An EPIC predictor of gestational '\n", " 'age and its application to newborns conceived by assisted '\n", " 'reproductive technologies.\" Clinical Epigenetics 13.1 (2021): '\n", " '82.',\n", " 'clock_name': 'epicga',\n", " 'data_type': 'methylation',\n", " 'doi': 'https://doi.org/10.1186/s13148-021-01055-z',\n", " 'notes': None,\n", " 'research_only': None,\n", " 'species': 'Homo sapiens',\n", " 'version': None,\n", " 'year': 2021}\n", "reference_values: None\n", "preprocess_name: None\n", "preprocess_dependencies: None\n", "postprocess_name: 'days_to_weeks'\n", "postprocess_dependencies: None\n", "features: ['cg12701018', 'cg00078456', 'cg14958032', 'cg00735586', 'cg09035049', 'cg23915699', 'cg24741609', 'cg00996847', 'cg12079303', 'cg20301308', 'cg21141647', 'cg13189264', 'cg16246545', 'cg06902698', 'cg01281797', 'cg01833485', 'cg12434132', 'cg06046912', 'cg11147204', 'cg19672145', 'cg02968445', 'cg09116068', 'cg07749613', 'cg21155834', 'cg15433843', 'cg12685296', 'cg22871331', 'cg25241559', 'cg06900004', 'cg20582941']... [Total elements: 176]\n", "base_model_features: None\n", "\n", "%==================================== Model Details ====================================%\n", "Model Structure:\n", "\n", "base_model: LinearModel(\n", " (linear): Linear(in_features=176, out_features=1, bias=True)\n", ")\n", "\n", "%==================================== Model Details ====================================%\n", "Model Parameters and Weights:\n", "\n", "base_model.linear.weight: [-0.09159819036722183, -2.3058528900146484, -0.4794044494628906, -11.715208053588867, -8.509488105773926, -0.5367807149887085, -0.32814541459083557, 1.0927908420562744, 1.626057744026184, -10.894654273986816, 1.7147382497787476, -8.59422492980957, 0.3499724566936493, 2.7312521934509277, 3.7085211277008057, 6.265093803405762, -3.1235597133636475, -0.5551669597625732, -4.767549991607666, 25.61239242553711, 1.6901012659072876, 1.5959044694900513, -32.38628387451172, -2.249823808670044, 11.97744369506836, 6.300745010375977, -0.7150956988334656, -0.45685043931007385, 3.390894889831543, -7.354003429412842]... [Tensor of shape torch.Size([1, 176])]\n", "base_model.linear.bias: tensor([293.4557])\n", "\n", "%==================================== Model Details ====================================%\n", "\n" ] } ], "source": [ "pya.utils.print_model_details(model)" ] }, { "cell_type": "markdown", "id": "9ee5b8cf", "metadata": {}, "source": [ "## Basic test" ] }, { "cell_type": "code", "execution_count": 13, "id": "4f77e279", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T20:24:58.910492Z", "iopub.status.busy": "2026-07-04T20:24:58.910415Z", "iopub.status.idle": "2026-07-04T20:24:58.920215Z", "shell.execute_reply": "2026-07-04T20:24:58.919766Z" } }, "outputs": [ { "data": { "text/plain": [ "tensor([[60.5326],\n", " [42.4761],\n", " [51.9958],\n", " [58.1296],\n", " [27.9050],\n", " [42.0799],\n", " [33.6746],\n", " [32.6965],\n", " [63.3254],\n", " [42.7455]], 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": "dc494a80", "metadata": {}, "source": [ "## Save torch model" ] }, { "cell_type": "code", "execution_count": 14, "id": "78d3742d", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T20:24:58.921643Z", "iopub.status.busy": "2026-07-04T20:24:58.921526Z", "iopub.status.idle": "2026-07-04T20:24:58.927373Z", "shell.execute_reply": "2026-07-04T20:24:58.926772Z" } }, "outputs": [], "source": [ "torch.save(model, f\"../weights/{model.metadata['clock_name']}.pt\")" ] }, { "cell_type": "markdown", "id": "d0da0589", "metadata": {}, "source": [ "## Clear directory\n", "" ] }, { "cell_type": "code", "execution_count": 15, "id": "e34db386", "metadata": { "execution": { "iopub.execute_input": "2026-07-04T20:24:58.929047Z", "iopub.status.busy": "2026-07-04T20:24:58.928919Z", "iopub.status.idle": "2026-07-04T20:24:58.933245Z", "shell.execute_reply": "2026-07-04T20:24:58.932768Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Deleted file: epic_ga_coefs.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 (ipykernel)", "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.13.11" } }, "nbformat": 4, "nbformat_minor": 5 }