Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /pfun-health_pfun-cma-model /pfun_cma_model /engine /calc.py
| """Numba-optimized calculations.""" | |
| import importlib | |
| import sys | |
| from pathlib import Path | |
| from typing import Literal | |
| from numpy import array, atleast_1d, clip, cos, broadcast_to | |
| from numpy import exp as np_exp | |
| from numpy import ( | |
| log, | |
| nan, | |
| ndarray, | |
| pi, | |
| piecewise, | |
| power, | |
| zeros, | |
| nansum, | |
| nanmean, | |
| nanmin, | |
| nanmax, | |
| ) | |
| from pandas import Series | |
| from pydantic import BaseModel | |
| from pfun_cma_model.engine.cma_model_params import CMAModelParams | |
| try: | |
| from pfun_cma_model.misc.decorators import check_is_numpy | |
| except ModuleNotFoundError: | |
| root_path = str(Path(__file__).parents[1]) | |
| mod_path = str(Path(__file__).parent) | |
| if root_path not in sys.path: | |
| sys.path.insert(0, root_path) | |
| if mod_path not in sys.path: | |
| sys.path.insert(0, mod_path) | |
| check_is_numpy = importlib.import_module( | |
| ".misc.decorators", package="pfun_cma_model" | |
| ).check_is_numpy | |
| def exp(x): | |
| """ | |
| Calculate the exponential of a number. Clip to avoid overflow. | |
| Parameters: | |
| x (float): The input number. | |
| Returns: | |
| float: The exponential of the input number. | |
| """ | |
| x_clipped = clip(x, -709, 709) | |
| result = np_exp(x_clipped) | |
| return result | |
| def expit_pfun(x): | |
| return 1.0 / (1.0 + exp(-2.0 * x)) | |
| def calc_vdep_current(v, v1, v2, A=1.0, B=1.0): | |
| return A * expit_pfun(B * (v - v1) / v2) | |
| def E_norm(x): | |
| y = 2.0 * (expit_pfun(2.0 * x) - 0.5) | |
| return y | |
| def _normalize(x, a, b): | |
| """normalize a flattened float array between a and b""" | |
| xmin, xmax = x.min(), x.max() | |
| return a + (b - a) * (x - xmin) / (xmax - xmin) | |
| def normalize(x, a: float = 0.0, b: float = 1.0): | |
| """normalize a flat 1-d ndarray[float] between a and b""" | |
| if isinstance(x, Series): | |
| x = x.to_numpy(dtype=float, na_value=nan) | |
| assert x.ndim < 2 | |
| x = array(x, dtype=float).flatten() | |
| return _normalize(x, a, b) | |
| class GlucoseRange_mgdl(BaseModel): | |
| g0: float = 70 | |
| g1: float = 180 | |
| g_s: float = 90 | |
| def g_range(self) -> ndarray: | |
| return array([self.g0, self.g1, self.g_s]) | |
| class GlucoseRange_mmoll(GlucoseRange_mgdl): | |
| g0: float = 3.7 | |
| g1: float = 11.0 | |
| g_s: float = 4.77 | |
| GlucoseUnits = Literal["mgdl", "mmoll"] | |
| def guess_glucose_units(values) -> GlucoseUnits: | |
| """Guess the glucose units (mgdl or mmoll).""" | |
| def calc_dist(x): | |
| gx0, gx1, gx_s = nanmin(values), nanmax(values), nanmean(values) | |
| gx = array([gx0, gx1, gx_s]) | |
| return ( | |
| "mgdl" | |
| if nansum((gx - GlucoseRange_mgdl().g_range) ** 2) | |
| < nansum((gx - GlucoseRange_mmoll().g_range) ** 2) | |
| else "mmoll" | |
| ) | |
| return calc_dist(values) | |
| def scale_glucose_units(units: GlucoseUnits): | |
| return { | |
| "mgdl": GlucoseRange_mgdl(), | |
| "mmoll": GlucoseRange_mmoll(), | |
| }[units].model_dump() | |
| def normalize_glucose(G, units: GlucoseUnits): | |
| """Normalize glucose (mg/dL -> [0.0, 2.0]). | |
| <0.9: low, | |
| 0.9: normal-low, | |
| 0.9-1.5: normal, | |
| >1.5: high | |
| see the graph: https://www.desmos.com/calculator/ii4qrawgjo | |
| """ | |
| glucose_range = scale_glucose_units(units) | |
| g0, g1, g_s = glucose_range["g0"], glucose_range["g1"], glucose_range["g_s"] | |
| numer = 8.95 * power((G - g_s), 3) + power((G - g0), 2) - power((G - g1), 2) | |
| return 2.0 * E(1e-4 * numer / (g1 - g0)) | |
| def Light(x): | |
| """ | |
| Calculates the light intensity based on the input value. | |
| Parameters: | |
| x (float): The input value. | |
| Returns: | |
| float: The calculated light intensity. | |
| """ | |
| return 2.0 / (1.0 + exp(2.0 * power(x, 2))) | |
| def E(x): | |
| """ | |
| Compute the exponential function for the given input. | |
| Parameters: | |
| x (float): The input value for the exponential function. | |
| Returns: | |
| float: The computed exponential value. | |
| """ | |
| return 1.0 / (1.0 + exp(-2.0 * x)) | |
| def meal_distr(Cm, t, toff): | |
| """Meal distribution function. | |
| Parameters | |
| ---------- | |
| Cm : float | |
| Cortisol temporal sensitivity coefficient (u/h). | |
| t : array_like | |
| Time (hours). | |
| toff : float | |
| Meal-relative time offset (hours). | |
| Returns | |
| ------- | |
| array_like | |
| Meal distribution function. | |
| """ | |
| return power(cos(2 * pi * Cm * (t + toff) / 24), 2) | |
| def K(x: ndarray): | |
| """ | |
| Defines the glucose response function. | |
| Apply a piecewise function to the input array `x`. | |
| Parameters: | |
| x (numpy.ndarray): The input array. | |
| Returns: | |
| numpy.ndarray: The result of applying the piecewise function to `x`. | |
| """ | |
| return piecewise( | |
| x, [x > 0.0, x <= 0.0], [lambda x_: exp(-power(log(2.0 * x_), 2)), 0.0] | |
| ) | |
| def vectorized_G( | |
| t: ndarray | float, | |
| I_E: ndarray | float, | |
| params: CMAModelParams, | |
| include_bias: bool = False, | |
| ): | |
| """Vectorized version of G(t, I_E, tm, taug, B, Cm, toff). | |
| Parameters | |
| ---------- | |
| t : array_like | float | |
| Time vector (hours). | |
| I_E : float | |
| Extracellular insulin (u*mg/mL). | |
| params: CMAModelParams | |
| Model parameters. | |
| include_bias: bool | |
| Whether to include bias. | |
| Returns | |
| ------- | |
| array_like | |
| G(t, I_E, tm, taug, B, Cm, toff). | |
| """ | |
| tm = atleast_1d(params.tM) | |
| t = atleast_1d(t) | |
| taug = broadcast_to(atleast_1d(params.taug), tm.shape) | |
| def Gtmp(tm_: float | ndarray, taug_: float | ndarray): | |
| k_G = K((t - atleast_1d(tm_)) / power(atleast_1d(taug_), 2)) | |
| return 1.3 * k_G / (1.0 + I_E) | |
| m = len(tm) | |
| n = len(t) | |
| j = 0 | |
| out = zeros((m, n), dtype=float) | |
| while j < m: | |
| gtmp = Gtmp(tm[j], taug[j]) | |
| out[j, :] = gtmp | |
| j = j + 1 | |
| if include_bias: | |
| out = out + params.B * ( | |
| 1.0 + meal_distr(params.Cm, t, params.toff) | |
| ) # ! apply bias constant. | |
| return out | |
Xet Storage Details
- Size:
- 5.91 kB
- Xet hash:
- f0421e676d7fbdf14085760509a583acc4f1ea988faf915555e43d7ef1a78f3f
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.