From 5c610d50e7b5d99a76b1008674e21a1a51bf714f Mon Sep 17 00:00:00 2001 From: DylanAdlard Date: Fri, 16 Oct 2026 20:14:56 +0100 Subject: [PATCH] random_effects and refactor --- .DS_Store | Bin 6148 -> 0 bytes .github/workflows/ci.yml | 0 .github/workflows/pypi.yaml | 0 .gitignore | 0 LICENSE | 0 README.md | 0 env.yml | 3 + pyproject.toml | 6 +- requirements.txt | 0 src/.DS_Store | Bin 6148 -> 0 bytes src/intreg/__init__.py | 0 src/intreg/intreg.py | 301 ++++++++++++----- src/intreg/meintreg.py | 648 +++++++++++++++++++++++++++--------- tests/__init__.py | 0 tests/test_IntReg.py | 85 +++++ tests/test_MeIntReg.py | 251 ++++++++------ 16 files changed, 939 insertions(+), 355 deletions(-) delete mode 100644 .DS_Store mode change 100644 => 100755 .github/workflows/ci.yml mode change 100644 => 100755 .github/workflows/pypi.yaml mode change 100644 => 100755 .gitignore mode change 100644 => 100755 LICENSE mode change 100644 => 100755 README.md mode change 100644 => 100755 env.yml mode change 100644 => 100755 pyproject.toml mode change 100644 => 100755 requirements.txt delete mode 100644 src/.DS_Store mode change 100644 => 100755 src/intreg/__init__.py mode change 100644 => 100755 src/intreg/intreg.py mode change 100644 => 100755 src/intreg/meintreg.py mode change 100644 => 100755 tests/__init__.py mode change 100644 => 100755 tests/test_IntReg.py diff --git a/.DS_Store b/.DS_Store deleted file mode 100644 index 96ce264f36d36a1c608c148dec6e1ca00c91ce7b..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 6148 zcmeHKzb^zq6n=9yxkDtP5>afY6Zao1If*EcTr0u-h$DO1JC69#Y*eD5S1Qyht&pfy z8V#aSh`#{en;CA#x}y@2dCAPTJMX=D-+ptub3;U8Y^{_f>LsEK8l%^R?h9i-w}hqi z$RJSg9N}U%UyQ1?M5G&V3OEJ+q5}NxdNfRnv_uW-{S}9Irmq_1a)mG|U@Vh;srQ8s zm!r17)Yf0C7~h8OGo(`by)IQ~jS5zE>KRBzm>iBT@29ViB!^G)RHG)7)=?H8@|jN$ z_|#~V8dRoL^mA0C1+)s4ZEoqk_R%KK<*SqPsk-FZW`2|N&oXTO^UOa3-WyHNyeC53pbOmLomM0 zXV%<(>U`Ae@R4g){mO6ERdavWW6x&GbSredQ@|!Z!1v2k3i mP^O^M+p)aht+*de8hk!q00WJ&LX5!N9|0+Y>zo3=s=ym+4Dmz& diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml old mode 100644 new mode 100755 diff --git a/.github/workflows/pypi.yaml b/.github/workflows/pypi.yaml old mode 100644 new mode 100755 diff --git a/.gitignore b/.gitignore old mode 100644 new mode 100755 diff --git a/LICENSE b/LICENSE old mode 100644 new mode 100755 diff --git a/README.md b/README.md old mode 100644 new mode 100755 diff --git a/env.yml b/env.yml old mode 100644 new mode 100755 index 9386a9d..4214620 --- a/env.yml +++ b/env.yml @@ -7,5 +7,8 @@ dependencies: - scipy - numpy - pytest + - mypy + - jax - pip - conda-forge::pytest-cov + diff --git a/pyproject.toml b/pyproject.toml old mode 100644 new mode 100755 index 1d63f2b..3440052 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "intreg" -version = "0.2.2" +version = "0.2.3" description = "A package for fitting an interval and mixed effect interval regression model to censored and/or uncensored point and/or interval data" readme = "README.md" authors = [ @@ -34,3 +34,7 @@ where = ["src"] [tool.pytest.ini_options] pythonpath = ["src"] testpaths = ["tests"] + +[[tool.mypy.overrides]] +module = ["scipy.*"] +ignore_missing_imports = true diff --git a/requirements.txt b/requirements.txt old mode 100644 new mode 100755 diff --git a/src/.DS_Store b/src/.DS_Store deleted file mode 100644 index dd9140d2acd01e7048edd9c536b8c66456c41bcb..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 6148 zcmeHK!AiqG5S@)xA`0zMJndOfCOoKW2oZYoYbt(%U*TEs z;G5m0?wXc(5|Np*^OD(_-PxCr=@5}>-FBNq4I+v$7^79FIl}WiN)kECI#8K4dek5E zo9(ka8@K!_oBR=z6+e_UTso3@`lm z(E3p=>zp+W9383yU_Klxsee z+gZ5|MVZ~PzBcZp5{sgR0bw9yV9DM#xc(n3?*GFexf2G2fq%t-s-^9;g(JDzS~?up uT8(jv!NPup#aRe0Oeuyhm*Nc!Bd}|}045F#i?BfCkAR^;lrZqC4159(&3ab= diff --git a/src/intreg/__init__.py b/src/intreg/__init__.py old mode 100644 new mode 100755 diff --git a/src/intreg/intreg.py b/src/intreg/intreg.py old mode 100644 new mode 100755 index 6fcc1b2..0a312f4 --- a/src/intreg/intreg.py +++ b/src/intreg/intreg.py @@ -1,7 +1,14 @@ +from typing import Any, Optional, cast + import numpy as np -from scipy.optimize import minimize +import numpy.typing as npt +from scipy.optimize import OptimizeResult, minimize +from scipy.special import log_ndtr from scipy.stats import norm +ArrayLike = npt.ArrayLike +FloatArray = npt.NDArray[np.float64] + class IntReg: """ @@ -9,32 +16,68 @@ class IntReg: using maximum likelihood estimation under a normal model. Attributes: - y_lower (array-like): Lower bound values of the observed intervals. - y_upper (array-like): Upper bound values of the observed intervals. - weights (array-like): Optional observation weights (defaults to 1 for all observations). + y_lower (array-like): One-dimensional lower bounds for the observations. + Use -np.inf for left-censored values. + y_upper (array-like): One-dimensional upper bounds for the observations. + Use np.inf for right-censored values. + weights (array-like): Optional observation weights. If None, each + observation has weight 1. """ - def __init__(self, y_lower, y_upper, weights=None): + result: OptimizeResult + + def __init__( + self, + y_lower: ArrayLike, + y_upper: ArrayLike, + weights: Optional[ArrayLike] = None, + ) -> None: """ Initialize the model with interval-bound data. Args: - y_lower (array-like): Lower bounds of the intervals. Use -np.inf for left-censored values. - y_upper (array-like): Upper bounds of the intervals. Use np.inf for right-censored values. - weights (array-like or None): Optional frequency or sampling weights. If None, all weights equal 1. - """ - self.y_lower = y_lower - self.y_upper = y_upper + y_lower (array-like): One-dimensional lower bounds. Use -np.inf + for left-censored values. + y_upper (array-like): One-dimensional upper bounds. Use np.inf + for right-censored values. + weights (array-like or None): Optional frequency or sampling + weights. If None, all weights equal 1. + + Raises: + ValueError: If the bounds or weights are not one-dimensional and + of equal length, or if no observations are supplied. - self.weights = np.ones_like(self.y_lower) if weights is None else np.asarray(weights) + Returns: + None + """ + self.y_lower = np.asarray(y_lower, dtype=float) + self.y_upper = np.asarray(y_upper, dtype=float) + if self.y_lower.ndim != 1 or self.y_upper.ndim != 1: + raise ValueError("y_lower and y_upper must be one-dimensional arrays.") + if self.y_lower.shape != self.y_upper.shape: + raise ValueError("y_lower and y_upper must have the same length.") + if self.y_lower.size == 0: + raise ValueError("At least one observation is required.") + + self.weights = ( + np.ones_like(self.y_lower) + if weights is None + else np.asarray(weights, dtype=float) + ) + if self.weights.shape != self.y_lower.shape: + raise ValueError("weights must have the same length as the interval bounds.") + self.L2_penalties: dict[str, Any] = {} @staticmethod - def interval_prob(y_low, y_high, mu, sigma): + def interval_prob( + y_low: ArrayLike, y_high: ArrayLike, mu: float, sigma: float + ) -> FloatArray: """ - Compute the likelihood contribution for each observation, covering exact, - left-censored, right-censored, and interval-censored outcomes under a - normal distribution. + Compute likelihood contributions on the probability scale. + + This method is retained for backwards compatibility. New code should + use `interval_log_likelihood` to avoid underflow for small likelihoods. Args: y_low (array-like): Lower interval bounds (may include -np.inf). @@ -44,104 +87,190 @@ def interval_prob(y_low, y_high, mu, sigma): Returns: np.ndarray: Likelihood contribution (density or probability) per - observation, shape (n,). Values are clipped to avoid underflow. + observation, shape (n,). Values are clipped to [1e-300, 1]. + """ + log_likelihood = IntReg.interval_log_likelihood(y_low, y_high, mu, sigma) + return np.clip(np.exp(log_likelihood), 1e-300, 1.0) + + + @staticmethod + def interval_log_likelihood( + y_low: ArrayLike, y_high: ArrayLike, mu: float, sigma: float + ) -> FloatArray: + """ + Compute per-observation log-likelihood contributions under a normal + distribution for exact, left-censored, right-censored, and + interval-censored observations. + + Args: + y_low (array-like): Lower interval bounds. Use -np.inf for + left-censored observations. + y_high (array-like): Upper interval bounds. Use np.inf for + right-censored observations. + mu (float): Mean of the normal distribution. + sigma (float): Standard deviation of the normal distribution. + Values below 1e-10 are clipped to 1e-10. + + Returns: + np.ndarray: Per-observation log-likelihood contributions, with + shape (n,). Exact observations contribute log densities; censored + and interval-censored observations contribute log probabilities. """ y_low = np.asarray(y_low, dtype=float) y_high = np.asarray(y_high, dtype=float) - sigma = np.maximum(sigma, 1e-10) + sigma_value = float(np.maximum(sigma, 1e-10)) + return IntReg._log_likelihood_contributions(y_low, y_high, mu, sigma_value) + - # Identify censoring types - points = (y_low == y_high) + @staticmethod + def _log_interval_prob(lower: FloatArray, upper: FloatArray) -> FloatArray: + """ + Compute the log probability of a standard normal value falling between + the supplied lower and upper bounds. + + The calculation uses the CDF in the left tail and the survival function + in the right tail to reduce loss of precision. + + Args: + lower (array-like): Standardized lower bounds of the intervals. + upper (array-like): Standardized upper bounds of the intervals. + + Returns: + np.ndarray: Log probabilities for the intervals, with the same + shape as the supplied bounds. + """ + logcdf_upper = log_ndtr(upper) + logcdf_lower = log_ndtr(lower) + logsf_lower = log_ndtr(-lower) + logsf_upper = log_ndtr(-upper) + + # Use CDFs in the left tail and survival functions in the right tail. + use_cdf = upper <= 0 + log_base = np.where(use_cdf, logcdf_upper, logsf_lower) + log_small = np.where(use_cdf, logcdf_lower, logsf_upper) + delta = np.minimum(log_small - log_base, -np.finfo(float).eps) + + cutoff = -np.log(2.0) + log_one_minus_exp = np.where( + delta < cutoff, + np.log1p(-np.exp(np.minimum(delta, cutoff))), + np.log(-np.expm1(np.maximum(delta, cutoff))), + ) + return cast(FloatArray, log_base + log_one_minus_exp) + + + @staticmethod + def _log_likelihood_contributions( + y_low: FloatArray, y_high: FloatArray, mu: float, sigma: float + ) -> FloatArray: + """ + Return log-likelihood contributions for exact, left-censored, + right-censored, and interval-censored observations. + + Args: + y_low (array-like): Lower bounds of the observations. Use -np.inf + for left-censored observations. + y_high (array-like): Upper bounds of the observations. Use np.inf + for right-censored observations. + mu (float): Mean of the normal distribution. + sigma (float): Standard deviation of the normal distribution. + + Returns: + np.ndarray: Log-likelihood contribution for each observation, + with shape (n,). + """ + points = y_low == y_high left_cens = np.isneginf(y_low) right_cens = np.isposinf(y_high) interval_cens = ~(points | left_cens | right_cens) + contributions = np.zeros_like(y_low, dtype=float) - p = np.zeros_like(y_low, dtype=float) - - # Point (exact) observations: PDF if np.any(points): - p[points] = norm.pdf(y_high[points], mu, sigma) - - # Left-censored observations: CDF + contributions[points] = norm.logpdf(y_high[points], loc=mu, scale=sigma) if np.any(left_cens): - p[left_cens] = norm.cdf((y_high[left_cens] - mu) / sigma) - - # Right-censored observations: survival function (1 - CDF) + z_upper = (y_high[left_cens] - mu) / sigma + contributions[left_cens] = log_ndtr(z_upper) if np.any(right_cens): - p[right_cens] = 1 - norm.cdf((y_low[right_cens] - mu) / sigma) - - # Interval-censored → CDF difference + z_lower = (y_low[right_cens] - mu) / sigma + contributions[right_cens] = log_ndtr(-z_lower) if np.any(interval_cens): - p[interval_cens] = ( - norm.cdf((y_high[interval_cens] - mu) / sigma) - - norm.cdf((y_low[interval_cens] - mu) / sigma) - ) + z_lower = (y_low[interval_cens] - mu) / sigma + z_upper = (y_high[interval_cens] - mu) / sigma + contributions[interval_cens] = IntReg._log_interval_prob(z_lower, z_upper) - # Avoid underflow / log(0) - p = np.clip(p, 1e-300, 1.0) - return p + return contributions - def log_L(self, params): + def log_L(self, params: ArrayLike) -> float: """ Compute the negative log-likelihood for the interval regression model. + Exact observations use the normal density, while censored observations + use their corresponding probabilities. The calculation is performed in + log space to reduce numerical underflow. The parameter vector is interpreted as: params[0] = mu params[1] = log(sigma) Args: - params (array-like): Model parameters [mu, log_sigma]. + params (array-like): Model parameters [mu, log_sigma], where + mu is the normal mean and log_sigma is the log standard + deviation. Returns: - float: Negative log-likelihood (with optional regularisation). + float: Negative log-likelihood, with optional L2 regularisation. """ - mu = params[0] - sigma = np.maximum(np.exp(params[1]), 1e-10) - p = IntReg.interval_prob(self.y_lower, self.y_upper, mu, sigma) - log_L = np.sum(self.weights * np.log(p)) + params_array = np.asarray(params, dtype=float) + mu = float(params_array[0]) + sigma = float(np.maximum(np.exp(params_array[1]), 1e-10)) + log_likelihood = self.interval_log_likelihood( + self.y_lower, self.y_upper, mu, sigma + ) + log_L = float(np.sum(self.weights * log_likelihood)) if hasattr(self, "L2_penalties") and len(self.L2_penalties) > 0: - log_L = self._apply_L2_regularisation(log_L, params) + log_L = self._apply_L2_regularisation(log_L, params_array) - return -log_L + return float(-log_L) - def _apply_L2_regularisation(self, log_L, params): + def _apply_L2_regularisation(self, log_L: float, params: ArrayLike) -> float: """ - Apply L2 (ridge) penalties to the log-likelihood. - These penalties are scaled by the number of observations. + Apply L2 (ridge) penalties to the log-likelihood. The penalties are + scaled by the number of observations. Args: log_L (float): Unpenalized log-likelihood. - params (array-like): Parameter vector, where the first n_fixed - parameters are penalized as 'beta' and the final parameter is - log(sigma). + params (array-like): Parameter vector [mu, log_sigma]. The first + n_fixed parameters (one by default) receive the beta penalty; + the final parameter receives the log(sigma) penalty. Returns: float: Regularized log-likelihood. """ + params_array = np.asarray(params, dtype=float) lambda_beta = self.L2_penalties.get("lambda_beta", 0.0) lambda_sigma = self.L2_penalties.get("lambda_sigma", 0.0) - n_fixed = self.L2_penalties.get("n_fixed", len(params) - 1) - beta = params[:n_fixed] # Fixed effects (first n_fixed params) - log_sigma = params[-1] # log(sigma) is the last parameter + n_fixed = self.L2_penalties.get("n_fixed", len(params_array) - 1) + beta = params_array[:n_fixed] # Fixed effects (first n_fixed params) + log_sigma = params_array[-1] # log(sigma) is the last parameter # Compute scaled L2 penalties penalty_beta = (lambda_beta / len(self.y_lower)) * np.sum(np.square(beta)) penalty_sigma = (lambda_sigma / len(self.y_lower)) * np.square(log_sigma) # Combine likelihood and regularization penalties - return log_L - penalty_beta - penalty_sigma + return float(log_L - penalty_beta - penalty_sigma) - def _initial_params(self): + def _initial_params(self) -> FloatArray: """ Generate automatic initial guesses for mu and log(sigma). - Midpoints of the intervals are used, and only finite midpoints - contribute to the initial estimates. The mean of finite midpoints is - mu, and their standard deviation (log-transformed) is log(sigma). + Finite interval midpoints are used to estimate mu and sigma. A small + positive floor is applied to sigma so identical midpoints still give + a finite starting value. If no finite midpoints are available, the + starting values are mu=0 and sigma=1. Returns: array: Initial parameter vector [mu, log(sigma)]. @@ -149,41 +278,51 @@ def _initial_params(self): # Mean of uncensored data midpoints = (self.y_lower + self.y_upper) / 2.0 valid_midpoints = np.where(np.isfinite(midpoints), midpoints, np.nan) - mu = np.nanmean(valid_midpoints) # Standard deviation of the valid midpoints (log-transformed for positivity) - sigma = np.nanstd(valid_midpoints) - sigma = np.log(sigma) + if np.all(np.isnan(valid_midpoints)): + mu = 0.0 + sigma = 1.0 + else: + mu = float(np.nanmean(valid_midpoints)) + sigma = max(float(np.nanstd(valid_midpoints)), 1e-6) + log_sigma = float(np.log(sigma)) - return np.array([mu, sigma]) + return np.array([mu, log_sigma], dtype=float) def fit( self, - method="BFGS", - initial_params=None, - bounds=None, - options=None, - L2_penalties=None, - ): + method: str = "BFGS", + initial_params: Optional[ArrayLike] = None, + bounds: Any = None, + options: Optional[dict[str, Any]] = None, + L2_penalties: Optional[dict[str, Any]] = None, + ) -> "IntReg": """ Fit the interval regression model by maximum likelihood estimation. - The optimization is performed over the parameters: - [mu, log(sigma)] + The optimization is performed over the parameters [mu, log(sigma)]. + The standard deviation is represented on the log scale to keep it + positive. Initial parameters are either user-supplied or generated automatically. - Optional L2 penalties may be applied to mu and/or log-sigma. + Optional L2 penalties may be applied to mu and log(sigma). Args: method (str, optional): Optimization method to use. Defaults to "BFGS". - initial_params (array-like, optional): Initial guesses for beta, random effects, and log(sigma). - If None, automatic initial guesses are generated. - bounds (array-like, optional): bounds for sigma - options (dict, optional): scipy minimisation options dictionary - L2_penalties (dict or None): Regularisation strengths for fixed and random effects {lambda_beta:..., lambda_u:...}. Defaults to None + initial_params (array-like, optional): Initial values for + [mu, log(sigma)]. If None, automatic initial values are used. + bounds (array-like, optional): Bounds passed to + scipy.optimize.minimize for the two parameters. + options (dict, optional): Options passed to + scipy.optimize.minimize. + L2_penalties (dict or None): Optional regularisation strengths, + such as {"lambda_beta": ..., "lambda_sigma": ...}. Defaults + to None. Returns: - IntReg: The fitted model instance containing the `result` attribute. + IntReg: The fitted model instance, with the optimizer result + available as `result`. """ self.L2_penalties = L2_penalties or {} diff --git a/src/intreg/meintreg.py b/src/intreg/meintreg.py old mode 100644 new mode 100755 index 9c57621..29057f7 --- a/src/intreg/meintreg.py +++ b/src/intreg/meintreg.py @@ -1,246 +1,564 @@ +from typing import Any, Dict, List, Optional, Tuple + import numpy as np -from scipy.optimize import minimize -from scipy.stats import norm +import numpy.typing as npt + +from numpy.polynomial.hermite import hermgauss +from scipy.optimize import OptimizeResult, minimize + +from jax import config +config.update("jax_enable_x64", True) # type: ignore[no-untyped-call] + +import jax +import jax.numpy as jnp +import jax.scipy as jsp + +ArrayLike = npt.ArrayLike +FloatArray = npt.NDArray[np.float64] class MeIntReg: """ Mixed-effects interval regression for censored, uncensored, and interval-censored data, - using maximum likelihood estimation under a normal model. + using marginal maximum likelihood under a Gaussian random-intercept model. + + Without random effects: + [beta..., log_sigma] + + With random effects: + [beta..., log_sigma, log_tau] + + where: + beta = fixed-effect coefficients + sigma = residual standard deviation + tau = random-intercept standard deviation + + Model: + y* = X beta + u_group + epsilon + u_group ~ N(0, tau^2) + epsilon ~ N(0, sigma^2) + + Random effects are integrated out using Gauss-Hermite quadrature. Attributes: - y_lower (array-like): Lower bound values of the intervals. - y_upper (array-like): Upper bound values of the intervals. - X (array-like): Covariate matrix for fixed effects. - random_effects (array-like or None): Group labels determining random-effect membership. - n_random_effects (int): Number of unique random-effect groups. + y_lower (np.ndarray): Lower bounds of the observation intervals. + y_upper (np.ndarray): Upper bounds of the observation intervals. + X (np.ndarray): Fixed-effect design matrix. + random_effects (np.ndarray or None): Encoded group labels, or None + when the model has no random effects. + n_random_effects (int): Number of random-effect groups. + result (OptimizeResult): Optimization result created by `fit`. """ - def __init__(self, y_lower, y_upper, X, random_effects=None): + result: OptimizeResult + + def __init__( + self, + y_lower: ArrayLike, + y_upper: ArrayLike, + X: ArrayLike, + random_effects: Optional[ArrayLike] = None, + quadrature_points: int = 20, + n_jobs: int = -1, + ) -> None: """ - Initialize the model with data. + Initialize the model. Args: - y_lower (array-like): Lower bounds of the intervals. Use -np.inf for left-censored values. - y_upper (array-like): Upper bounds of the intervals. Use np.inf for right-censored values. - X (array-like): Covariate matrix for fixed effects. - random_effects (array-like, optional): Group labels for random intercepts. - If None, the model includes only fixed effects. + y_lower (array-like): Lower interval bounds. Use -np.inf for + left-censored observations. + y_upper (array-like): Upper interval bounds. Use np.inf for + right-censored observations. + X (array-like): Fixed-effect design matrix, with one row per + observation. + random_effects (array-like or None): Optional group labels + defining random-intercept membership. If None, only fixed + effects are fitted. + quadrature_points (int): Number of Gauss-Hermite quadrature points + used to integrate the random effects. Defaults to 20. + n_jobs (int): Retained for backwards compatibility. + + Returns: + None """ - self.y_lower = y_lower - self.y_upper = y_upper - self.X = X + + self.y_lower = np.asarray(y_lower, dtype=float) + self.y_upper = np.asarray(y_upper, dtype=float) + self.X = np.asarray(X, dtype=float) + self.quadrature_points = quadrature_points + self.n_jobs = n_jobs + + self._y_lower = jnp.asarray(self.y_lower) + self._y_upper = jnp.asarray(self.y_upper) + self._X = jnp.asarray(self.X) + + self.random_effects: Optional[Any] = None + self.n_random_effects: int = 0 + self.group_indices: Optional[List[Any]] = None + self._group_indices: Optional[List[Any]] = None + self.gh_nodes: Optional[Any] = None + self.gh_weights: Optional[Any] = None + self.log_gh_weights: Optional[Any] = None + self._gh_nodes: Optional[Any] = None + self._log_gh_weights: Optional[Any] = None if random_effects is not None: - self.random_effects = np.array(random_effects) - self.n_random_effects = len(np.unique(random_effects)) + random_effects = np.asarray(random_effects) + _, group_codes = np.unique(random_effects, return_inverse=True) + + self.random_effects = group_codes + self.n_random_effects = len(np.unique(group_codes)) + self.group_indices = [np.flatnonzero(group_codes == g) for g in range(self.n_random_effects)] + self._group_indices = [jnp.asarray(indices, dtype=jnp.int32) for indices in self.group_indices] + + self.gh_nodes, self.gh_weights = hermgauss(quadrature_points) + self.log_gh_weights = np.log(self.gh_weights) + + self._gh_nodes = jnp.asarray(self.gh_nodes) + self._log_gh_weights = jnp.asarray(self.log_gh_weights) else: self.random_effects = None self.n_random_effects = 0 + self.group_indices = None + self._group_indices = None + self.gh_nodes = None + self.gh_weights = None + self.log_gh_weights = None + self._gh_nodes = None + self._log_gh_weights = None + + self.L2_penalties: Dict[str, float] = {} + self._value_and_grad: Any = None + self._hessian_fn: Any = None + + def _unpack_params( + self, params: Any + ) -> Tuple[Any, Any, Optional[Any]]: + """ + Unpack the model parameter vector. - def _compute_effects( - self, params: np.ndarray - ) -> tuple[np.ndarray, np.ndarray | None, np.ndarray]: + Args: + params (array-like): Model parameters. The first `X.shape[1]` + values are fixed effects, followed by log_sigma and, when + random effects are present, log_tau. + + Returns: + tuple: Fixed-effect coefficients, log residual standard deviation, + and log random-effect standard deviation (or None). """ - Extract fixed effects (beta), random effects (u), and compute the linear predictor (mu). - If random effects, mu is: + n_fixed = self.X.shape[1] + beta = params[:n_fixed] + log_sigma = params[n_fixed] + log_tau = params[n_fixed + 1] if self.random_effects is not None else None + + return beta, log_sigma, log_tau - mu = X @ beta + u[group_index] + @staticmethod + def _log1mexp(x: Any) -> Any: + """ + Compute log(1 - exp(x)) stably for x <= 0. - Otherwise: + Args: + x (array-like): Values less than or equal to zero. - mu = X @ beta. + Returns: + jax.Array: Stable log(1 - exp(x)) values. + """ + + x = jnp.minimum(x, -1e-15) + cutoff = -jnp.log(2.0) + + x_left = jnp.minimum(x, cutoff - 1e-15) + x_right = jnp.maximum(x, cutoff) + + left = jnp.log1p(-jnp.exp(x_left)) + right = jnp.log(-jnp.expm1(x_right)) + + return jnp.where(x < cutoff, left, right) + + @staticmethod + def _log_interval_prob(lower: Any, upper: Any) -> Any: + """ + Compute log[P(lower < Z < upper)] for Z ~ N(0, 1) stably. Args: - params (array-like): Parameter vector containing beta, random effects, - and log(sigma). + lower (array-like): Standardized lower interval bounds. + upper (array-like): Standardized upper interval bounds. Returns: - tuple: (beta, u, mu) - beta (array): Fixed-effect coefficients. - u (array or None): Random-effect coefficients (or None if not included). - mu (array): Mean for each observation given fixed and random effects. + jax.Array: Log probabilities for the intervals. """ - n_fixed = self.X.shape[1] - beta = params[:n_fixed] - if self.random_effects is not None: - u = params[n_fixed : n_fixed + self.n_random_effects] - mu = np.dot(self.X, beta) + u[self.random_effects] - else: - u = None - mu = np.dot(self.X, beta) + logcdf_upper = jsp.special.log_ndtr(upper) + logcdf_lower = jsp.special.log_ndtr(lower) + + delta_cdf = jnp.minimum(logcdf_lower - logcdf_upper, -1e-15) + log_prob_cdf = logcdf_upper + MeIntReg._log1mexp(delta_cdf) + + logsf_lower = jsp.special.log_ndtr(-lower) + logsf_upper = jsp.special.log_ndtr(-upper) + + delta_sf = jnp.minimum(logsf_upper - logsf_lower, -1e-15) + log_prob_sf = logsf_lower + MeIntReg._log1mexp(delta_sf) + + return jnp.where(upper <= 0, log_prob_cdf, log_prob_sf) - return beta, u, mu + @staticmethod + def _normal_logpdf(y: Any, mu: Any, sigma: Any) -> Any: + """ + Compute the log-density of a normal distribution. + + Args: + y (array-like): Observed values. + mu (array-like): Normal means. + sigma (float or array-like): Normal standard deviation. - def log_L(self, params): + Returns: + jax.Array: Normal log-density values. """ - Compute the negative log-likelihood for the mixed-effects interval regression model. - Censored, uncensored, and interval-censored contributions are computed - using normal PDF/CDF relationships. Random intercepts shift the mean - according to group membership. + z = (y - mu) / sigma + return -0.5 * z**2 - jnp.log(sigma) - 0.5 * jnp.log(2.0 * jnp.pi) + + def _observation_loglik(self, indices: Any, mu: Any, sigma: Any) -> Any: + """ + Compute the conditional log-likelihood for selected observations. Args: - params (array-like): Parameters to be estimated: [beta, u, log(sigma)]. - - Returns: - float: Negative log-likelihood (with optional L2 penalties). - """ - _, _, mu = self._compute_effects(params) - sigma = np.maximum( - np.exp(params[-1]), 1e-10 - ) # Log-transformed sigma for positivity - - log_L = 0 - - # Likelihood function for point data - points = self.y_upper == self.y_lower - if np.any(points): - log_L += np.sum(norm.logpdf((self.y_upper[points] - mu[points]) / sigma)) - - # Likelihood function for left-censored values - left_censored = np.isin(self.y_lower, -np.inf) - if np.any(left_censored): - log_L += np.sum( - norm.logcdf((self.y_upper[left_censored] - mu[left_censored]) / sigma) - ) - - # Likelihood function for right-censored values - right_censored = np.isin(self.y_upper, np.inf) - if np.any(right_censored): - log_L += np.sum( - np.log( - 1 - - norm.cdf( - (self.y_lower[right_censored] - mu[right_censored]) / sigma - ) - ) - ) - - # Likelihood function for intervals - interval_censored = ~left_censored & ~right_censored & ~points - if np.any(interval_censored): - log_L += np.sum( - np.log( - norm.cdf( - (self.y_upper[interval_censored] - mu[interval_censored]) - / sigma - ) - - norm.cdf( - (self.y_lower[interval_censored] - mu[interval_censored]) - / sigma - ) - ) - ) - - if hasattr(self, "L2_penalties") and len(self.L2_penalties) > 0: - log_L = self._apply_L2_regularisation(log_L, params) - return -log_L + indices (array-like): Indices of observations to include. + mu (array-like): Conditional means for the observations. + sigma (float): Residual standard deviation. + + Returns: + jax.Array: Sum of the log-likelihood contributions. + """ + + y_lower = self._y_lower[indices] + y_upper = self._y_upper[indices] + + points = y_upper == y_lower + left = jnp.isneginf(y_lower) + right = jnp.isposinf(y_upper) + interval = ~(points | left | right) + + safe_y = jnp.where(jnp.isfinite(y_upper), y_upper, 0.0) + point_ll = self._normal_logpdf(safe_y, mu, sigma) + point_ll = jnp.where(points, point_ll, 0.0) - def _apply_L2_regularisation(self, log_L, params): + left_upper = jnp.where(left, y_upper, mu) + z_upper = (left_upper - mu) / sigma + left_ll = jnp.where(left, jsp.special.log_ndtr(z_upper), 0.0) + + right_lower = jnp.where(right, y_lower, mu) + z_lower = (right_lower - mu) / sigma + right_ll = jnp.where(right, jsp.special.log_ndtr(-z_lower), 0.0) + + safe_lower = jnp.where(interval, y_lower, 0.0) + safe_upper = jnp.where(interval, y_upper, 1.0) + + interval_lower = (safe_lower - mu) / sigma + interval_upper = (safe_upper - mu) / sigma + interval_ll = self._log_interval_prob(interval_lower, interval_upper) + interval_ll = jnp.where(interval, interval_ll, 0.0) + + return jnp.sum(point_ll + left_ll + right_ll + interval_ll) + + def _group_loglik( + self, indices: Any, fixed_mu: Any, sigma: Any, tau: Any + ) -> Any: """ - Apply L2 regularization (ridge penalties) to the log-likelihood. - Each penalty is scaled by the number of observations. + Marginal log-likelihood contribution for one random-effect group. + All quadrature points are evaluated simultaneously. Args: - log_L (float): Unpenalized log-likelihood value. - params (array-like): Model parameters [beta, u, log(sigma)]. + indices (array-like): Indices belonging to the group. + fixed_mu (array-like): Fixed-effect means for all observations. + sigma (float): Residual standard deviation. + tau (float): Random-intercept standard deviation. Returns: - float: Regularized log-likelihood value. + jax.Array: Marginal log-likelihood contribution for the group. """ + + assert self._gh_nodes is not None + assert self._log_gh_weights is not None + + y_lower = self._y_lower[indices] + y_upper = self._y_upper[indices] + group_fixed_mu = fixed_mu[indices] + + u = jnp.sqrt(2.0) * tau * self._gh_nodes + mu = group_fixed_mu[None, :] + u[:, None] + + points = y_upper == y_lower + left = jnp.isneginf(y_lower) + right = jnp.isposinf(y_upper) + interval = ~(points | left | right) + + safe_y = jnp.where(jnp.isfinite(y_upper), y_upper, 0.0) + point_ll = self._normal_logpdf(safe_y[None, :], mu, sigma) + point_ll = jnp.where(points[None, :], point_ll, 0.0) + + left_upper = jnp.where(left[None, :], y_upper[None, :], mu) + z_upper = (left_upper - mu) / sigma + left_ll = jnp.where(left[None, :], jsp.special.log_ndtr(z_upper), 0.0) + + right_lower = jnp.where(right[None, :], y_lower[None, :], mu) + z_lower = (right_lower - mu) / sigma + right_ll = jnp.where(right[None, :], jsp.special.log_ndtr(-z_lower), 0.0) + + safe_lower = jnp.where(interval, y_lower, 0.0) + safe_upper = jnp.where(interval, y_upper, 1.0) + + interval_lower = (safe_lower[None, :] - mu) / sigma + interval_upper = (safe_upper[None, :] - mu) / sigma + interval_ll = self._log_interval_prob(interval_lower, interval_upper) + interval_ll = jnp.where(interval[None, :], interval_ll, 0.0) + + node_loglik = jnp.sum(point_ll + left_ll + right_ll + interval_ll, axis=1) + + return jsp.special.logsumexp(self._log_gh_weights + node_loglik) - 0.5 * jnp.log(jnp.pi) + + def _apply_L2_regularisation(self, log_L: Any, params: Any) -> Any: + """ + Apply optional L2 regularisation to the log-likelihood. + + Args: + log_L (float or jax.Array): Unregularised log-likelihood. + params (array-like): Model parameter vector containing fixed + effects and log standard deviations. + + Returns: + jax.Array: Regularised log-likelihood. + """ + lambda_beta = self.L2_penalties.get("lambda_beta", 0.0) - lambda_u = self.L2_penalties.get("lambda_u", 0.0) - lambda_sigma = self.L2_penalties.get( - "lambda_sigma", 0.0 - ) # New regularization term + lambda_sigma = self.L2_penalties.get("lambda_sigma", 0.0) + lambda_tau = self.L2_penalties.get("lambda_tau", 0.0) N = self.X.shape[0] + beta, log_sigma, log_tau = self._unpack_params(params) - n_fixed = self.X.shape[1] - beta = params[:n_fixed] - u = params[n_fixed : n_fixed + self.n_random_effects] - log_sigma = params[-1] + penalty_beta = (lambda_beta / N) * jnp.sum(beta**2) + penalty_sigma = (lambda_sigma / N) * log_sigma**2 + penalty_tau = (lambda_tau / N) * log_tau**2 if log_tau is not None else 0.0 + + return log_L - penalty_beta - penalty_sigma - penalty_tau + + def _neg_loglik(self, params: Any) -> Any: + """ + Compute the negative marginal log-likelihood. + + Args: + params (array-like): Fixed-effect coefficients and log standard + deviations, ordered as described in the class documentation. + + Returns: + jax.Array: Negative marginal log-likelihood. + """ + + beta, log_sigma, log_tau = self._unpack_params(params) + + sigma = jnp.exp(log_sigma) + fixed_mu = self._X @ beta + + if self.random_effects is None: + indices = jnp.arange(self._y_lower.shape[0], dtype=jnp.int32) + log_L = self._observation_loglik(indices, fixed_mu, sigma) + else: + assert log_tau is not None + assert self._group_indices is not None + tau = jnp.exp(log_tau) + log_L = jnp.array(0.0, dtype=jnp.float64) - # Compute scaled L2 penalties - penalty_beta = (lambda_beta / N) * np.sum(np.square(beta)) - penalty_u = (lambda_u / N) * np.sum(np.square(u)) - penalty_sigma = (lambda_sigma / N) * log_sigma**2 # Regularize log(sigma) + for indices in self._group_indices: + log_L += self._group_loglik(indices, fixed_mu, sigma, tau) - # Combine likelihood and regularization penalties - return log_L - penalty_beta - penalty_u - penalty_sigma + if len(self.L2_penalties) > 0: + log_L = self._apply_L2_regularisation(log_L, params) + + return -log_L - def _initial_params(self): + def log_L(self, params: ArrayLike) -> float: """ - Generate automatic initial values for all parameters. + Compute the negative marginal log-likelihood for supplied parameters. - Initial beta is obtained from a least-squares regression of the finite - midpoints of the intervals on X. Random effects are initialized to zero. - The standard deviation of the finite midpoints is used to initialize log(sigma). + Args: + params (array-like): Fixed-effect coefficients and log standard + deviations, ordered as described in the class documentation. Returns: - array: Initial parameter vector [beta, random effects, log(sigma)]. + float: Negative marginal log-likelihood. + """ + + return float(self._neg_loglik(jnp.asarray(params, dtype=jnp.float64))) + + def _initial_params(self) -> FloatArray: """ - # Mean of uncensored data for initial beta estimate + Generate automatic initial parameter values. + + Without random effects: + [beta..., log_sigma] + + With random effects: + [beta..., log_sigma, log_tau] + + Returns: + np.ndarray: Initial parameter vector for the model. + """ + midpoints = (self.y_lower + self.y_upper) / 2.0 valid_mask = np.isfinite(midpoints) - # Filter X and midpoints to exclude rows with non-finite midpoints - X, midpoints = self.X[valid_mask], midpoints[valid_mask] + X_valid = self.X[valid_mask] + midpoints_valid = midpoints[valid_mask] - # Solve linear regression for beta - beta_init = np.linalg.lstsq(X, midpoints, rcond=None)[0] + beta_init = np.linalg.lstsq(X_valid, midpoints_valid, rcond=None)[0] + + sigma_init = max(np.nanstd(midpoints_valid), 1e-6) + log_sigma_init = np.log(sigma_init) if self.random_effects is not None: - u_init = np.zeros(self.n_random_effects) - else: - u_init = [] + tau_init = 0.5 + log_tau_init = np.log(tau_init) + return np.concatenate([beta_init, [log_sigma_init, log_tau_init]]) - # Standard deviation of the valid midpoints for sigma (log-transformed for positivity) - sigma = np.nanstd(midpoints) - sigma = np.log(sigma) + return np.concatenate([beta_init, [log_sigma_init]]) - return np.concatenate([beta_init, u_init, [sigma]]) + def _objective_with_grad(self, params: ArrayLike) -> Tuple[float, FloatArray]: + """ + Return the objective value and gradient for scipy.optimize.minimize. + + Args: + params (array-like): Model parameter vector. + + Returns: + tuple: Objective value as a float and gradient as a NumPy array. + """ + + if self._value_and_grad is None: + self._value_and_grad = jax.jit(jax.value_and_grad(self._neg_loglik)) + + value, gradient = self._value_and_grad( + jnp.asarray(np.asarray(params, dtype=float), dtype=jnp.float64) + ) + + return float(value), np.asarray(gradient, dtype=float) + + def hessian(self, params: Optional[ArrayLike] = None) -> FloatArray: + """ + Calculate the Hessian of the negative marginal log-likelihood. + + If params is None, use the fitted parameter vector. + + Args: + params (array-like or None): Parameter vector at which to compute + the Hessian. If None, the fitted parameters are used. + + Returns: + np.ndarray: Hessian matrix of the negative marginal + log-likelihood. + + Raises: + ValueError: If params is None and the model has not been fitted. + """ + + if params is None: + if not hasattr(self, "result"): + raise ValueError("The model must be fitted before requesting the Hessian.") + params = self.result.x + + if self._hessian_fn is None: + self._hessian_fn = jax.jit(jax.hessian(self._neg_loglik)) + + H = self._hessian_fn(jnp.asarray(params, dtype=jnp.float64)) + return np.asarray(H, dtype=float) + + def __getstate__(self) -> Dict[str, Any]: + """ + Remove compiled functions before serialization. + + Returns: + dict: Model state with compiled JAX functions removed. + """ + state = self.__dict__.copy() + state["_value_and_grad"] = None + state["_hessian_fn"] = None + return state + + + def __setstate__(self, state: Dict[str, Any]) -> None: + """ + Restore model state after deserialization. + + Args: + state (dict): Previously serialized model state. + + Returns: + None + """ + self.__dict__.update(state) + self._value_and_grad = None + self._hessian_fn = None def fit( self, - method="BFGS", - initial_params=None, - bounds=None, - options=None, - L2_penalties=None, - ): + method: str = "BFGS", + initial_params: Optional[ArrayLike] = None, + bounds: Any = None, + options: Optional[Dict[str, Any]] = None, + L2_penalties: Optional[Dict[str, float]] = None, + ) -> "MeIntReg": """ - Fit the mixed-effects interval regression model using maximum likelihood estimation. + Fit the interval-regression model using marginal maximum likelihood. - If no initial parameters are supplied, they are generated automatically. - Optional L2 penalties may be applied to fixed effects, random effects, - and log(sigma). + Parameters are ordered as [beta..., log_sigma] without random effects + and [beta..., log_sigma, log_tau] with random effects. Args: - method (str, optional): Optimization method passed to scipy.optimize.minimize. - Defaults to "BFGS". - initial_params (array-like, optional): Initial values for - [beta, random effects, log(sigma)]. If None, automatic initial - guesses are generated. - bounds (array-like, optional): Parameter bounds passed directly to - minimize, applying in order to all parameters. - options (dict, optional): Options dictionary for the optimizer. - L2_penalties (dict or None): Optional L2 regularisation strengths, - e.g. {"lambda_beta": ..., "lambda_u": ..., "lambda_sigma": ...}. - Defaults to None. + method (str): Optimization method passed to + scipy.optimize.minimize. Defaults to "BFGS". + initial_params (array-like or None): Optional initial parameter + vector. If None, initial values are generated automatically. + bounds (sequence or None): Optional parameter bounds passed to + scipy.optimize.minimize. + options (dict or None): Options passed to + scipy.optimize.minimize. + L2_penalties (dict or None): Optional regularisation strengths, + such as {"lambda_beta": ..., "lambda_sigma": ..., + "lambda_tau": ...}. Returns: - MeIntReg: The fitted model instance, with the optimization result. + MeIntReg: The fitted model instance, with the optimization result + available as `result`. """ - self.L2_penalties = L2_penalties or {} + + self.L2_penalties = dict(L2_penalties or {}) if initial_params is None: initial_params = self._initial_params() + initial_params = np.asarray(initial_params, dtype=float) + + self._value_and_grad = jax.jit(jax.value_and_grad(self._neg_loglik)) + self._hessian_fn = None + self._value_and_grad(jnp.asarray(initial_params, dtype=jnp.float64)) + + value0, grad0 = self._objective_with_grad(initial_params) + + print("INITIAL OBJECTIVE:", value0) + print("INITIAL OBJECTIVE FINITE:", np.isfinite(value0)) + print("INITIAL GRADIENT FINITE:", np.isfinite(grad0).all()) + print("INITIAL MAX |GRAD|:", np.max(np.abs(grad0))) + self.result = minimize( - self.log_L, initial_params, method=method, bounds=bounds, options=options + self._objective_with_grad, + initial_params, + method=method, + jac=True, + bounds=bounds, + options=options, ) + return self diff --git a/tests/__init__.py b/tests/__init__.py old mode 100644 new mode 100755 diff --git a/tests/test_IntReg.py b/tests/test_IntReg.py old mode 100644 new mode 100755 index 829f0c4..38430b8 --- a/tests/test_IntReg.py +++ b/tests/test_IntReg.py @@ -1,8 +1,12 @@ +import importlib +import importlib.metadata import pytest import numpy as np +import intreg from intreg import IntReg from scipy.optimize import OptimizeResult from scipy.stats import norm +from importlib.metadata import PackageNotFoundError @pytest.fixture @@ -101,6 +105,49 @@ def test_initial_params( ), f"Failed for data {y_lower, y_upper}: expected log(sigma) {expected_log_sigma}, got {initial_log_sigma}" +def test_initial_params_handles_zero_spread_and_no_finite_midpoints(): + """Test initial values remain finite for degenerate and censored data.""" + same_points = np.array([2.0, 2.0, 2.0]) + model = IntReg(same_points, same_points) + initial_params = model._initial_params() + assert np.all(np.isfinite(initial_params)) + assert np.isclose(initial_params[0], 2.0) + assert np.isclose(initial_params[1], np.log(1e-6)) + + model = IntReg([-np.inf, -np.inf], [0.0, 1.0]) + initial_params = model._initial_params() + assert np.all(np.isfinite(initial_params)) + assert np.allclose(initial_params, [0.0, 0.0]) + + +def test_input_arrays_must_have_matching_lengths(): + """Test bounds and weights are checked against the observation count.""" + with pytest.raises(ValueError, match="one-dimensional"): + IntReg([[1.0, 2.0]], [[1.0, 2.0]]) + + with pytest.raises(ValueError, match="same length"): + IntReg([1.0, 2.0], [1.0]) + + with pytest.raises(ValueError, match="At least one observation"): + IntReg([], []) + + with pytest.raises(ValueError, match="weights"): + IntReg([1.0, 2.0], [1.0, 2.0], weights=[1.0]) + + +def test_package_version_fallback_when_metadata_is_missing(monkeypatch): + """Test package version defaults when distribution metadata is unavailable.""" + def missing_version(_): + raise PackageNotFoundError("intreg") + + with monkeypatch.context() as patch: + patch.setattr(importlib.metadata, "version", missing_version) + importlib.reload(intreg) + assert intreg.__version__ == "0.0.0" + + importlib.reload(intreg) + + def test_log_L( simple_point_data, left_censored_data, @@ -137,6 +184,44 @@ def test_log_L( ), f"log_L output should be positive for {description}, got {log_likelihood}" +def test_log_L_is_finite_for_extreme_intervals(): + """Test log-space likelihood remains finite for narrow tail intervals.""" + y_lower = np.array([40.0, -np.inf, 40.0]) + y_upper = np.array([40.000001, 0.0, np.inf]) + model = IntReg(y_lower, y_upper) + + negative_log_likelihood = model.log_L(np.array([0.0, 0.0])) + assert np.isfinite(negative_log_likelihood) + + +def test_interval_log_likelihood_returns_each_observation_contribution(): + """Test log-likelihood contributions for each censoring type.""" + y_lower = np.array([1.0, -np.inf, 2.0, 40.0]) + y_upper = np.array([1.0, 0.0, np.inf, 40.000001]) + contributions = IntReg.interval_log_likelihood( + y_lower, y_upper, mu=0.0, sigma=1.0 + ) + + assert contributions.shape == y_lower.shape + assert np.all(np.isfinite(contributions)) + assert np.isclose(contributions[0], norm.logpdf(1.0)) + assert np.isclose(contributions[1], norm.logcdf(0.0)) + assert np.isclose(contributions[2], norm.logsf(2.0)) + + +def test_interval_prob_remains_compatible_with_log_likelihood_method(): + """Test the probability-scale helper remains available for existing callers.""" + y_lower = np.array([1.0, -np.inf, 2.0]) + y_upper = np.array([1.0, 0.0, np.inf]) + + probabilities = IntReg.interval_prob(y_lower, y_upper, mu=0.0, sigma=1.0) + log_likelihood = IntReg.interval_log_likelihood( + y_lower, y_upper, mu=0.0, sigma=1.0 + ) + + assert np.allclose(probabilities, np.clip(np.exp(log_likelihood), 1e-300, 1.0)) + + def test_simple_point_data_fit(simple_point_data): y_lower, y_upper = simple_point_data model = IntReg(y_lower, y_upper).fit() diff --git a/tests/test_MeIntReg.py b/tests/test_MeIntReg.py index 47df8de..7542e44 100644 --- a/tests/test_MeIntReg.py +++ b/tests/test_MeIntReg.py @@ -1,5 +1,6 @@ import pytest import numpy as np +import pickle from intreg import MeIntReg from scipy.optimize import OptimizeResult @@ -36,7 +37,7 @@ def right_censored_data(): @pytest.fixture def mixed_interval_and_point_data(): - """Fixture for mixed interval and point data.""" + """Fixture for mixed interval-censored and point data.""" y_lower = np.array([1, 2, 3, 3]) y_upper = np.array([1, np.inf, 4, 3]) X = np.array([[1, 0], [1, 1], [1, 2], [1, 3]]) @@ -46,7 +47,7 @@ def mixed_interval_and_point_data(): @pytest.fixture def clear_interval_censored_data(): - """Fixture for clear interval-censored data with obvi ous midpoints.""" + """Fixture for interval-censored data with clear midpoints.""" y_lower = np.array([1, 2, 3, 4]) y_upper = np.array([2, 3, 4, 5]) X = np.array([[1, 0], [1, 1], [1, 2], [1, 3]]) @@ -61,162 +62,196 @@ def test_initial_params( mixed_interval_and_point_data, clear_interval_censored_data, ): - """Test _initial_params method for mixed-effects interval regression.""" + """Test automatic starting values for models with random intercepts.""" test_cases = [ (simple_point_data, "simple point data"), - (left_censored_data, "left censored data"), - (right_censored_data, "right censored data"), - (mixed_interval_and_point_data, "mixed inteval and point data"), - (clear_interval_censored_data, "clear interval censored data"), + (left_censored_data, "left-censored data"), + (right_censored_data, "right-censored data"), + (mixed_interval_and_point_data, "mixed interval and point data"), + (clear_interval_censored_data, "interval-censored data"), ] for (y_lower, y_upper, X, random_effects), description in test_cases: model = MeIntReg(y_lower, y_upper, X, random_effects) - initial_params = model._initial_params() - beta_init = initial_params[: X.shape[1]] - u_init = initial_params[X.shape[1] : X.shape[1] + model.n_random_effects] - log_sigma_init = initial_params[-1] - # Assert beta is computed via linear regression midpoints = (y_lower + y_upper) / 2.0 valid_mask = np.isfinite(midpoints) - X, midpoints = X[valid_mask], midpoints[valid_mask] - expected_beta = np.linalg.lstsq(X, midpoints, rcond=None)[0] + expected_beta = np.linalg.lstsq(X[valid_mask], midpoints[valid_mask], rcond=None)[0] + expected_log_sigma = np.log(max(np.nanstd(midpoints[valid_mask]), 1e-6)) + assert initial_params.shape == (X.shape[1] + 2,) assert np.allclose( - beta_init, expected_beta, atol=1e-4 - ), f"Failed for {description}: beta initialization incorrect" - - # Assert random effects are initialized as zeros - assert np.allclose( - u_init, 0, atol=1e-4 - ), f"Failed for {description}: random effects not initialized to zero" - - # Assert log_sigma is a log of the standard deviation of midpoints - expected_log_sigma = np.log(np.nanstd(midpoints)) + initial_params[: X.shape[1]], expected_beta, atol=1e-4 + ), f"Failed for {description}: fixed-effect starting values are incorrect" assert np.isclose( - log_sigma_init, expected_log_sigma, atol=1e-4 - ), f"Failed for {description}: log(sigma) initialization incorrect" + initial_params[-2], expected_log_sigma, atol=1e-4 + ), f"Failed for {description}: log(sigma) starting value is incorrect" + assert np.isclose( + initial_params[-1], np.log(0.5), atol=1e-4 + ), f"Failed for {description}: log(tau) starting value is incorrect" + + +def test_initial_params_without_random_effects(simple_point_data): + """Test automatic starting values when random effects are omitted.""" + y_lower, y_upper, X, _ = simple_point_data + model = MeIntReg(y_lower, y_upper, X) + initial_params = model._initial_params() + + assert initial_params.shape == (X.shape[1] + 1,) + assert np.all(np.isfinite(initial_params)) + + +def test_no_random_effects_likelihood_gradient_and_hessian(): + """Test likelihood derivatives when the model has no random effects.""" + y_lower = np.array([1.0, -np.inf, 2.0, 0.0]) + y_upper = np.array([1.0, 0.0, np.inf, 2.0]) + X = np.ones((4, 1)) + model = MeIntReg(y_lower, y_upper, X) + likelihood_params = np.array([0.5, 0.0]) + + # Exercise point, left-censored, right-censored, and interval branches. + assert np.isfinite(model.log_L(likelihood_params)) + _, censored_gradient = model._objective_with_grad(likelihood_params) + assert np.all(np.isfinite(censored_gradient)) + + grouped_model = MeIntReg( + y_lower, y_upper, X, random_effects=np.array([0, 1, 1, 2]) + ) + grouped_params = grouped_model._initial_params() + _, grouped_gradient = grouped_model._objective_with_grad(grouped_params) + assert np.all(np.isfinite(grouped_gradient)) + + # Use finite point data to check derivatives independently of censoring masks. + point_model = MeIntReg([1.0, 2.0, 3.0], [1.0, 2.0, 3.0], np.ones((3, 1))) + params = np.array([2.0, 0.0]) + objective, gradient = point_model._objective_with_grad(params) + assert np.isfinite(objective) + assert gradient.shape == params.shape + assert np.all(np.isfinite(gradient)) + + point_model.result = OptimizeResult(x=params) + hessian = point_model.hessian() + assert hessian.shape == (len(params), len(params)) + assert np.all(np.isfinite(hessian)) + + +def test_hessian_requires_fit_when_params_are_omitted(simple_point_data): + """Test Hessian reports a clear error before fitting without parameters.""" + y_lower, y_upper, X, _ = simple_point_data + model = MeIntReg(y_lower, y_upper, X) + + with pytest.raises(ValueError, match="must be fitted"): + model.hessian() + + +def test_serialization_clears_compiled_functions(): + """Test compiled JAX functions are recreated after serialization.""" + y_lower = np.array([1.0, 2.0, 3.0]) + X = np.ones((3, 1)) + model = MeIntReg(y_lower, y_lower, X) + params = np.array([2.0, 0.0]) + model._objective_with_grad(params) + model.hessian(params) + + restored_model = pickle.loads(pickle.dumps(model)) + assert restored_model._value_and_grad is None + assert restored_model._hessian_fn is None + assert np.isfinite(restored_model.log_L(params)) def test_log_L( simple_point_data, left_censored_data, right_censored_data, + mixed_interval_and_point_data, clear_interval_censored_data, ): - """Test log_L using parameters generated by _initial_params on all data types.""" + """Test the negative marginal log-likelihood for each observation type.""" - # Define test cases as tuples: (data, description) test_cases = [ (simple_point_data, "point data"), (right_censored_data, "right-censored data"), (left_censored_data, "left-censored data"), + (mixed_interval_and_point_data, "mixed interval and point data"), (clear_interval_censored_data, "interval-censored data"), ] for (y_lower, y_upper, X, random_effects), description in test_cases: model = MeIntReg(y_lower, y_upper, X, random_effects) - params = model._initial_params() - log_likelihood = model.log_L(params) + negative_log_likelihood = model.log_L(params) assert isinstance( - log_likelihood, float - ), f"log_L output should be float for {description}" + negative_log_likelihood, float + ), f"log_L output should be a float for {description}" assert np.isfinite( - log_likelihood + negative_log_likelihood ), f"log_L output should be finite for {description}" - assert ( - log_likelihood > 0 - ), f"log_L output should be positive for {description}, got {log_likelihood}" - - -def test_simple_point_data_fit(simple_point_data): - y_lower, y_upper, X, random_effects = simple_point_data - model = MeIntReg(y_lower, y_upper, X, random_effects).fit() - result = model.result - print(result) - print(result.x[0], result.x[1]) - assert isinstance(result, OptimizeResult) - assert np.isclose(result.x[0], 0.6, atol=1e-1) # Expect mu near 0.6 - assert np.isclose(result.x[1], 1, atol=1e-1) # Expect sigma near 1 -def test_left_censored_data_fit(left_censored_data): - y_lower, y_upper, X, random_effects = left_censored_data +@pytest.mark.parametrize( + "fixture_name", + [ + "simple_point_data", + "left_censored_data", + "right_censored_data", + "mixed_interval_and_point_data", + "clear_interval_censored_data", + ], +) +def test_fit_returns_finite_result(request, fixture_name): + """Test fitting returns finite parameter estimates for each data type.""" + y_lower, y_upper, X, random_effects = request.getfixturevalue(fixture_name) model = MeIntReg(y_lower, y_upper, X, random_effects).fit() - result = model.result - print(result.x[0], result.x[1]) - assert isinstance(result, OptimizeResult) - assert np.isclose(result.x[0], -0.5, atol=1e-1) - assert np.isclose(result.x[1], 1, atol=1e-1) - -def test_right_censored_data_fit(right_censored_data): - y_lower, y_upper, X, random_effects = right_censored_data - model = MeIntReg(y_lower, y_upper, X, random_effects).fit() - result = model.result - print(result.x[0], result.x[1]) - assert isinstance(result, OptimizeResult) - assert np.isclose(result.x[0], 1.2, atol=1e-1) - assert np.isclose(result.x[1], 1.1, atol=1e-1) - - -def test_mixed_interval_and_point_data_fit(mixed_interval_and_point_data): - y_lower, y_upper, X, random_effects = mixed_interval_and_point_data - model = MeIntReg(y_lower, y_upper, X, random_effects).fit() - result = model.result - print(result.x[0], result.x[1]) - assert isinstance(result, OptimizeResult) - assert np.isclose(result.x[0], 1.7, atol=1e-1) - assert np.isclose(result.x[1], 0.4, atol=1e-1) - - -def test_clear_interval_censored_data_fit(clear_interval_censored_data): - y_lower, y_upper, X, random_effects = clear_interval_censored_data - model = MeIntReg(y_lower, y_upper, X, random_effects).fit() - result = model.result - print(result.x[0], result.x[1]) - assert isinstance(result, OptimizeResult) - assert np.isclose(result.x[0], 1.5, atol=1e-1) - assert np.isclose(result.x[1], 1, atol=1e-1) + assert isinstance(model.result, OptimizeResult) + assert model.result.x.shape == (X.shape[1] + 2,) + assert np.all(np.isfinite(model.result.x)) + assert np.isfinite(model.result.fun) def test_meintreg_regularisation(): - y_low = np.array([1.0, 1.0, 2.0, 2.0]) - y_high = y_low.copy() # exact values + """Test L2 penalties for fixed effects and both standard deviations.""" + y_lower = np.array([1.0, 1.0, 2.0, 2.0]) + y_upper = y_lower.copy() # exact values X = np.ones((4, 1)) # intercept-only fixed effect groups = np.array([0, 0, 1, 1]) # random intercept groups - model = MeIntReg(y_low, y_high, X, random_effects=groups) + model = MeIntReg(y_lower, y_upper, X, random_effects=groups) model.L2_penalties = { "lambda_beta": 2.0, - "lambda_u": 3.0, "lambda_sigma": 4.0, + "lambda_tau": 3.0, } - # params = [beta, u0, u1, log_sigma] - params = np.array([1.5, 0.5, -0.5, -1.0]) - unpen = -10.0 - - # expected penalties: - # N = 4 - # beta penalty: (2/4)*(1.5^2) = (0.5)*2.25 = 1.125 - # u penalty: (3/4)*(0.5^2+(-0.5)^2) = 0.75*(0.25+0.25)=0.75*0.5 = 0.375 - # sigma pen: (4/4)*(1.0^2) = 1.0 - expected = unpen - (1.125 + 0.375 + 1.0) - - direct = model._apply_L2_regularisation(unpen, params) + + # params = [beta, log_sigma, log_tau] + params = np.array([1.5, -1.0, -0.5]) + unpenalised = -10.0 + expected = unpenalised - ( + (2.0 / 4) * 1.5**2 + + (4.0 / 4) * (-1.0) ** 2 + + (3.0 / 4) * (-0.5) ** 2 + ) + direct = model._apply_L2_regularisation(unpenalised, params) assert np.isclose(direct, expected) - - # check that log_L applies penalties - no_penalty = MeIntReg(y_low, y_high, X, groups).log_L(params) - model.L2_penalties = {"lambda_beta": 50.0, "lambda_u": 50.0, "lambda_sigma": 0.0} - with_penalty = model.log_L(params) - assert with_penalty > no_penalty # more penalty → larger negative log-likelihood - model = MeIntReg(y_low, y_high, X, groups) - model.fit(L2_penalties={"lambda_beta": 1.0, "lambda_u": 1.0, "lambda_sigma": 1.0}) + no_penalty = MeIntReg(y_lower, y_upper, X, groups).log_L(params) + model.L2_penalties = { + "lambda_beta": 50.0, + "lambda_sigma": 0.0, + "lambda_tau": 0.0, + } + with_penalty = model.log_L(params) + assert with_penalty > no_penalty # more penalty increases negative log-likelihood + + model = MeIntReg(y_lower, y_upper, X, groups) + model.fit( + L2_penalties={ + "lambda_beta": 1.0, + "lambda_sigma": 1.0, + "lambda_tau": 1.0, + } + ) assert hasattr(model, "result") - assert model.result.x is not None + assert model.result.x is not None