From 50a3e8c6613de05ed9c97bb820d12c811232ea70 Mon Sep 17 00:00:00 2001 From: Janos Gabler Date: Fri, 30 Oct 2026 07:56:56 +0100 Subject: [PATCH 1/3] Rewrite the BHHH algorithm Replace the bhhh optimizer by a new implementation: an eigendecomposition of the scaled outer product of gradients with an eigenvalue floor, a box-constrained step with bounds, an Armijo line search with interpolation and step doubling, and stopping on the decrement g'(J'J)^-1 g. Trial points at which the objective or its derivative fails are rejected. The docstring documents the requirements on the objective function. Co-Authored-By: Claude Opus 5.5 --- docs/source/algorithms.md | 47 +- docs/source/refs.bib | 31 + src/optimagic/algorithms.py | 72 +++ src/optimagic/optimizers/_bhhh/__init__.py | 0 src/optimagic/optimizers/_bhhh/bhhh_loop.py | 340 ++++++++++ src/optimagic/optimizers/_bhhh/linalg.py | 166 +++++ src/optimagic/optimizers/_bhhh/line_search.py | 286 ++++++++ src/optimagic/optimizers/_bhhh/subproblem.py | 102 +++ src/optimagic/optimizers/bhhh.py | 256 +++++--- .../optimization/test_many_algorithms.py | 4 +- tests/optimagic/optimizers/_bhhh/__init__.py | 0 .../optimagic/optimizers/_bhhh/test_linalg.py | 127 ++++ .../optimizers/_bhhh/test_line_search.py | 215 ++++++ .../optimizers/_bhhh/test_subproblem.py | 95 +++ tests/optimagic/optimizers/test_bhhh.py | 612 +++++++++++++++--- 15 files changed, 2152 insertions(+), 201 deletions(-) create mode 100644 src/optimagic/optimizers/_bhhh/__init__.py create mode 100644 src/optimagic/optimizers/_bhhh/bhhh_loop.py create mode 100644 src/optimagic/optimizers/_bhhh/linalg.py create mode 100644 src/optimagic/optimizers/_bhhh/line_search.py create mode 100644 src/optimagic/optimizers/_bhhh/subproblem.py create mode 100644 tests/optimagic/optimizers/_bhhh/__init__.py create mode 100644 tests/optimagic/optimizers/_bhhh/test_linalg.py create mode 100644 tests/optimagic/optimizers/_bhhh/test_line_search.py create mode 100644 tests/optimagic/optimizers/_bhhh/test_subproblem.py diff --git a/docs/source/algorithms.md b/docs/source/algorithms.md index c8c379b25..1df07f3ef 100644 --- a/docs/source/algorithms.md +++ b/docs/source/algorithms.md @@ -825,30 +825,43 @@ We implement a few algorithms from scratch. They are currently considered experi ```{eval-rst} .. dropdown:: bhhh - .. code-block:: + **How to use this algorithm:** + + .. code-block:: python + + import optimagic as om + from optimagic.optimizers.bhhh import LineSearch + + om.maximize( + fun=loglike_contributions, + params=start_params, + algorithm=om.algos.bhhh( + convergence_decrement_tol=1e-8, + globalization=LineSearch(expansion="none"), + ), + ) - "bhhh" + or using the string interface: - Minimize a likelihood function using the BHHH algorithm. + .. code-block:: python - BHHH (:cite:`Berndt1974`) can - and should ONLY - be used for minimizing - (or maximizing) a likelihood. It is similar to the Newton-Raphson - algorithm, but replaces the Hessian matrix with the outer product of the - gradient. This approximation is based on the information matrix equality - (:cite:`Halbert1982`) and is thus only vaid when minimizing (or maximizing) - a likelihood. + om.maximize( + fun=loglike_contributions, + params=start_params, + algorithm="bhhh", + algo_options={"convergence_decrement_tol": 1e-8}, + ) - The criterion function :func:`func` should return a dictionary with - at least the entry ``{"contributions": array_or_pytree}`` where ``array_or_pytree`` - contains the likelihood contributions of each individual. + ``loglike_contributions`` must be decorated with ``om.mark.likelihood`` and return + one log-likelihood contribution per independent unit. - bhhh supports the following options: + **Description and available options:** - - **convergence.gtol_abs** (float): Stopping criterion for the - gradient tolerance. Default is 1e-8. - - **stopping.maxiter** (int): Maximum number of iterations. - If reached, terminate. Default is 200. + .. autoclass:: optimagic.optimizers.bhhh.BHHH + + **Options of the line search:** + .. autoclass:: optimagic.optimizers.bhhh.LineSearch ``` ```{eval-rst} diff --git a/docs/source/refs.bib b/docs/source/refs.bib index 215f3471e..7f1c844eb 100644 --- a/docs/source/refs.bib +++ b/docs/source/refs.bib @@ -1114,4 +1114,35 @@ @article{Ni2013 year = {2013} } +@book{Train2009, + author = {Train, Kenneth E.}, + title = {Discrete Choice Methods with Simulation}, + edition = {2}, + publisher = {Cambridge University Press}, + address = {Cambridge}, + year = {2009}, +} + +@article{Dennis1981, + author = {Dennis, John E., Jr. and Gay, David M. and Welsch, Roy E.}, + title = {An Adaptive Nonlinear Least-Squares Algorithm}, + journal = {ACM Transactions on Mathematical Software}, + volume = {7}, + number = {3}, + pages = {348--368}, + year = {1981}, + doi = {10.1145/355958.355965}, +} + +@article{Bunch1988, + author = {Bunch, David S.}, + title = {A Comparison of Algorithms for Maximum Likelihood Estimation of Choice Models}, + journal = {Journal of Econometrics}, + volume = {38}, + number = {1--2}, + pages = {145--167}, + year = {1988}, + doi = {10.1016/0304-4076(88)90031-0}, +} + @Comment{jabref-meta: databaseType:bibtex;} diff --git a/src/optimagic/algorithms.py b/src/optimagic/algorithms.py index 139476489..360f63fae 100644 --- a/src/optimagic/algorithms.py +++ b/src/optimagic/algorithms.py @@ -362,6 +362,11 @@ class BoundedGradientBasedLeastSquaresLocalAlgorithms(AlgoSelection): scipy_ls_trf: Type[ScipyLSTRF] = ScipyLSTRF +@dataclass(frozen=True) +class BoundedGradientBasedLikelihoodLocalAlgorithms(AlgoSelection): + bhhh: Type[BHHH] = BHHH + + @dataclass(frozen=True) class GradientBasedLocalNonlinearConstrainedScalarAlgorithms(AlgoSelection): ipopt: Type[Ipopt] = Ipopt @@ -992,6 +997,7 @@ def NonlinearConstrained( @dataclass(frozen=True) class BoundedGradientBasedLocalAlgorithms(AlgoSelection): + bhhh: Type[BHHH] = BHHH fides: Type[Fides] = Fides iminuit_migrad: Type[IminuitMigrad] = IminuitMigrad ipopt: Type[Ipopt] = Ipopt @@ -1012,6 +1018,10 @@ class BoundedGradientBasedLocalAlgorithms(AlgoSelection): def LeastSquares(self) -> BoundedGradientBasedLeastSquaresLocalAlgorithms: return BoundedGradientBasedLeastSquaresLocalAlgorithms() + @property + def Likelihood(self) -> BoundedGradientBasedLikelihoodLocalAlgorithms: + return BoundedGradientBasedLikelihoodLocalAlgorithms() + @property def NonlinearConstrained( self, @@ -1085,6 +1095,10 @@ def Bounded(self) -> BoundedGradientBasedLeastSquaresLocalAlgorithms: class GradientBasedLikelihoodLocalAlgorithms(AlgoSelection): bhhh: Type[BHHH] = BHHH + @property + def Bounded(self) -> BoundedGradientBasedLikelihoodLocalAlgorithms: + return BoundedGradientBasedLikelihoodLocalAlgorithms() + @dataclass(frozen=True) class BoundedGradientBasedNonlinearConstrainedAlgorithms(AlgoSelection): @@ -1152,6 +1166,15 @@ def Local(self) -> BoundedGradientBasedLeastSquaresLocalAlgorithms: return BoundedGradientBasedLeastSquaresLocalAlgorithms() +@dataclass(frozen=True) +class BoundedGradientBasedLikelihoodAlgorithms(AlgoSelection): + bhhh: Type[BHHH] = BHHH + + @property + def Local(self) -> BoundedGradientBasedLikelihoodLocalAlgorithms: + return BoundedGradientBasedLikelihoodLocalAlgorithms() + + @dataclass(frozen=True) class GradientBasedNonlinearConstrainedScalarAlgorithms(AlgoSelection): ipopt: Type[Ipopt] = Ipopt @@ -2112,6 +2135,15 @@ def Parallel(self) -> BoundedLeastSquaresLocalParallelAlgorithms: return BoundedLeastSquaresLocalParallelAlgorithms() +@dataclass(frozen=True) +class BoundedLikelihoodLocalAlgorithms(AlgoSelection): + bhhh: Type[BHHH] = BHHH + + @property + def GradientBased(self) -> BoundedGradientBasedLikelihoodLocalAlgorithms: + return BoundedGradientBasedLikelihoodLocalAlgorithms() + + @dataclass(frozen=True) class BoundedLocalParallelAlgorithms(AlgoSelection): pounders: Type[Pounders] = Pounders @@ -2380,6 +2412,7 @@ def Scalar(self) -> GradientBasedLocalScalarAlgorithms: @dataclass(frozen=True) class BoundedGradientBasedAlgorithms(AlgoSelection): + bhhh: Type[BHHH] = BHHH fides: Type[Fides] = Fides iminuit_migrad: Type[IminuitMigrad] = IminuitMigrad ipopt: Type[Ipopt] = Ipopt @@ -2407,6 +2440,10 @@ def Global(self) -> BoundedGlobalGradientBasedAlgorithms: def LeastSquares(self) -> BoundedGradientBasedLeastSquaresAlgorithms: return BoundedGradientBasedLeastSquaresAlgorithms() + @property + def Likelihood(self) -> BoundedGradientBasedLikelihoodAlgorithms: + return BoundedGradientBasedLikelihoodAlgorithms() + @property def Local(self) -> BoundedGradientBasedLocalAlgorithms: return BoundedGradientBasedLocalAlgorithms() @@ -2506,6 +2543,10 @@ def Local(self) -> GradientBasedLeastSquaresLocalAlgorithms: class GradientBasedLikelihoodAlgorithms(AlgoSelection): bhhh: Type[BHHH] = BHHH + @property + def Bounded(self) -> BoundedGradientBasedLikelihoodAlgorithms: + return BoundedGradientBasedLikelihoodAlgorithms() + @property def Local(self) -> GradientBasedLikelihoodLocalAlgorithms: return GradientBasedLikelihoodLocalAlgorithms() @@ -3178,6 +3219,7 @@ def Scalar(self) -> GlobalParallelScalarAlgorithms: @dataclass(frozen=True) class BoundedLocalAlgorithms(AlgoSelection): + bhhh: Type[BHHH] = BHHH fides: Type[Fides] = Fides iminuit_migrad: Type[IminuitMigrad] = IminuitMigrad ipopt: Type[Ipopt] = Ipopt @@ -3219,6 +3261,10 @@ def GradientFree(self) -> BoundedGradientFreeLocalAlgorithms: def LeastSquares(self) -> BoundedLeastSquaresLocalAlgorithms: return BoundedLeastSquaresLocalAlgorithms() + @property + def Likelihood(self) -> BoundedLikelihoodLocalAlgorithms: + return BoundedLikelihoodLocalAlgorithms() + @property def NonlinearConstrained(self) -> BoundedLocalNonlinearConstrainedAlgorithms: return BoundedLocalNonlinearConstrainedAlgorithms() @@ -3342,6 +3388,10 @@ def Parallel(self) -> LeastSquaresLocalParallelAlgorithms: class LikelihoodLocalAlgorithms(AlgoSelection): bhhh: Type[BHHH] = BHHH + @property + def Bounded(self) -> BoundedLikelihoodLocalAlgorithms: + return BoundedLikelihoodLocalAlgorithms() + @property def GradientBased(self) -> GradientBasedLikelihoodLocalAlgorithms: return GradientBasedLikelihoodLocalAlgorithms() @@ -3548,6 +3598,19 @@ def Parallel(self) -> BoundedLeastSquaresParallelAlgorithms: return BoundedLeastSquaresParallelAlgorithms() +@dataclass(frozen=True) +class BoundedLikelihoodAlgorithms(AlgoSelection): + bhhh: Type[BHHH] = BHHH + + @property + def GradientBased(self) -> BoundedGradientBasedLikelihoodAlgorithms: + return BoundedGradientBasedLikelihoodAlgorithms() + + @property + def Local(self) -> BoundedLikelihoodLocalAlgorithms: + return BoundedLikelihoodLocalAlgorithms() + + @dataclass(frozen=True) class BoundedParallelAlgorithms(AlgoSelection): nevergrad_bo: Type[NevergradBayesOptim] = NevergradBayesOptim @@ -4059,6 +4122,7 @@ def Scalar(self) -> LocalScalarAlgorithms: @dataclass(frozen=True) class BoundedAlgorithms(AlgoSelection): bayes_opt: Type[BayesOpt] = BayesOpt + bhhh: Type[BHHH] = BHHH fides: Type[Fides] = Fides gfo_differential_evolution: Type[GFODifferentialEvolution] = ( GFODifferentialEvolution @@ -4165,6 +4229,10 @@ def GradientFree(self) -> BoundedGradientFreeAlgorithms: def LeastSquares(self) -> BoundedLeastSquaresAlgorithms: return BoundedLeastSquaresAlgorithms() + @property + def Likelihood(self) -> BoundedLikelihoodAlgorithms: + return BoundedLikelihoodAlgorithms() + @property def Local(self) -> BoundedLocalAlgorithms: return BoundedLocalAlgorithms() @@ -4383,6 +4451,10 @@ def Parallel(self) -> LeastSquaresParallelAlgorithms: class LikelihoodAlgorithms(AlgoSelection): bhhh: Type[BHHH] = BHHH + @property + def Bounded(self) -> BoundedLikelihoodAlgorithms: + return BoundedLikelihoodAlgorithms() + @property def GradientBased(self) -> GradientBasedLikelihoodAlgorithms: return GradientBasedLikelihoodAlgorithms() diff --git a/src/optimagic/optimizers/_bhhh/__init__.py b/src/optimagic/optimizers/_bhhh/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/src/optimagic/optimizers/_bhhh/bhhh_loop.py b/src/optimagic/optimizers/_bhhh/bhhh_loop.py new file mode 100644 index 000000000..396edfc4a --- /dev/null +++ b/src/optimagic/optimizers/_bhhh/bhhh_loop.py @@ -0,0 +1,340 @@ +"""Main loop of the BHHH algorithm.""" + +import warnings +from typing import Literal, cast + +import numpy as np +from numpy.typing import NDArray + +from optimagic.exceptions import UserFunctionRuntimeError +from optimagic.optimization.algorithm import InternalOptimizeResult +from optimagic.optimization.internal_optimization_problem import ( + InternalOptimizationProblem, +) +from optimagic.optimizers._bhhh.linalg import ( + OPGFactorization, + condition_number, + factorize_opg, + rank, + weakly_identified_directions, +) +from optimagic.optimizers._bhhh.line_search import ( + MIN_SHRINK_FACTOR, + LineSearch, + LineSearchResult, + line_search, +) +from optimagic.optimizers._bhhh.subproblem import ( + compute_step, + max_feasible_step_length, +) + +StopReason = Literal[ + "convergence_decrement_tol", + "convergence_ftol_abs", + "convergence_xtol_rel", + "stopping_maxiter", + "stopping_maxfun", + "line_search_failure", +] + +CONVERGENCE_REASONS = ( + "convergence_decrement_tol", + "convergence_ftol_abs", + "convergence_xtol_rel", +) + + +def bhhh_internal( + problem: InternalOptimizationProblem, + x0: NDArray[np.float64], + line_search_options: LineSearch, + decrement_tol: float, + ftol_abs: float, + xtol_rel: float, + maxiter: int, + maxfun: int, +) -> InternalOptimizeResult: + """Minimize a sum of contributions with the BHHH algorithm. + + Args: + problem: The internal optimization problem. Its fun returns the contributions, + whose sum is minimized, and its jac their Jacobian. + x0: Start parameters, shape (k,). + line_search_options: Options of the line search. + decrement_tol: Stop if the decrement is at most this. + ftol_abs: Stop if an accepted step improves the objective by at most this. + Disabled if zero. + xtol_rel: Stop if the relative BHHH step is at most this. Disabled if zero. + maxiter: Maximum number of accepted steps. + maxfun: Maximum number of evaluations of the objective. + + Returns: + The optimization result. Success means that a convergence criterion is met. + + """ + lower, upper = _get_bounds(problem, len(x0)) + + raw_fun_value, jac = problem.fun_and_jac(x0) + fun_value = cast(NDArray[np.float64], raw_fun_value) + x = x0 + criterion = float(np.sum(fun_value)) + + zero_columns = np.flatnonzero(np.all(jac == 0, axis=0)) + if zero_columns.size > 0: + warnings.warn(_zero_columns_message(zero_columns)) + + n_fun_evals = 1 + n_jac_evals = 1 + n_iterations = 0 + n_backtracks = 0 + n_expansions = 0 + n_failed_fun_evals = 0 + n_failed_jac_evals = 0 + last_error: str | None = None + stop_reason: StopReason | None = None + + while True: + factorization = factorize_opg(jac) + step, decrement = compute_step(factorization, lower - x, upper - x) + relative_step = np.max(np.abs(step) / np.maximum(1, np.abs(x))) + + if decrement <= decrement_tol: + stop_reason = "convergence_decrement_tol" + elif stop_reason is not None: + pass + elif xtol_rel > 0 and relative_step <= xtol_rel: + stop_reason = "convergence_xtol_rel" + elif n_iterations >= maxiter: + stop_reason = "stopping_maxiter" + elif n_fun_evals >= maxfun: + stop_reason = "stopping_maxfun" + if stop_reason is not None: + break + + # The step is a descent direction whenever the decrement is positive; this only + # fails through rounding errors if the decrement tolerance is tiny. + slope = float(factorization.gradient @ step) + if not slope < 0: + stop_reason = "line_search_failure" + break + + max_step_length = min( + line_search_options.max_step_factor, + max_feasible_step_length(x, step, lower, upper), + ) + initial_step_length = 1.0 + backtracks_left = line_search_options.max_backtracks + is_retry = False + while True: + search = line_search( + fun=problem.fun, # ty: ignore[invalid-argument-type] + x=x, + criterion=criterion, + direction=step, + slope=slope, + lower=lower, + upper=upper, + options=line_search_options, + initial_step_length=initial_step_length, + max_step_length=max_step_length, + expand=not is_retry, + max_backtracks=backtracks_left, + max_fun_evals=maxfun - n_fun_evals, + ) + n_fun_evals += search.n_fun_evals + n_backtracks += search.n_backtracks + n_expansions += search.n_expansions + n_failed_fun_evals += search.n_failed_fun_evals + if search.last_error is not None: + last_error = _error_text(search.last_error) + if search.status != "success": + break + # Derivatives that cannot be evaluated or are not finite at an accepted + # point, e.g. numerical derivatives close to a region where the objective + # is undefined, reject the point. + n_jac_evals += 1 + try: + new_jac = problem.jac(search.x) + except UserFunctionRuntimeError as e: + n_failed_jac_evals += 1 + last_error = _error_text(e) + backtracks_left -= search.n_backtracks + 1 + if backtracks_left < 0: + search = _as_failure(search) + break + initial_step_length = MIN_SHRINK_FACTOR * search.step_length + is_retry = True + continue + break + + if search.status == "max_fun_evals": + stop_reason = "stopping_maxfun" + break + if search.status == "max_backtracks": + stop_reason = "line_search_failure" + break + + n_iterations += 1 + if ftol_abs > 0 and criterion - search.criterion <= ftol_abs: + stop_reason = "convergence_ftol_abs" + x = search.x + fun_value = cast(NDArray[np.float64], search.fun_value) + criterion = search.criterion + jac = new_jac + + weak_directions = weakly_identified_directions(factorization) + if weak_directions or jac.shape[0] < jac.shape[1]: + warnings.warn(_identification_message(weak_directions, *jac.shape)) + + info = { + "stop_reason": stop_reason, + "decrement": decrement, + "rank": rank(factorization), + "condition_number": condition_number(factorization), + "active_lower_bounds": np.flatnonzero(x <= lower).tolist(), + "active_upper_bounds": np.flatnonzero(x >= upper).tolist(), + "n_backtracks": n_backtracks, + "n_expansions": n_expansions, + "n_failed_fun_evals": n_failed_fun_evals, + "n_failed_jac_evals": n_failed_jac_evals, + } + + return InternalOptimizeResult( + x=x, + fun=fun_value, + success=stop_reason in CONVERGENCE_REASONS, + message=_message( + stop_reason=stop_reason, + decrement=decrement, + decrement_tol=decrement_tol, + factorization=factorization, + n_failed_evals=n_failed_fun_evals + n_failed_jac_evals, + last_error=last_error, + ), + n_fun_evals=n_fun_evals, + n_jac_evals=n_jac_evals, + n_iterations=n_iterations, + jac=factorization.gradient, + info=info, + ) + + +def _get_bounds( + problem: InternalOptimizationProblem, n_params: int +) -> tuple[NDArray[np.float64], NDArray[np.float64]]: + lower = problem.bounds.lower + upper = problem.bounds.upper + lower = np.full(n_params, -np.inf) if lower is None else lower + upper = np.full(n_params, np.inf) if upper is None else upper + return lower, upper + + +def _as_failure(search: LineSearchResult) -> LineSearchResult: + return LineSearchResult( + status="max_backtracks", + step_length=search.step_length, + x=search.x, + fun_value=None, + criterion=search.criterion, + n_fun_evals=search.n_fun_evals, + n_backtracks=search.n_backtracks, + n_expansions=search.n_expansions, + n_failed_fun_evals=search.n_failed_fun_evals, + last_error=search.last_error, + ) + + +def _error_text(error: UserFunctionRuntimeError) -> str: + """Describe an error together with the user error that caused it.""" + cause = error.__cause__ + if cause is None: + return str(error) + return f"{error} {type(cause).__name__}: {cause}" + + +def _message( + stop_reason: StopReason, + decrement: float, + decrement_tol: float, + factorization: OPGFactorization, + n_failed_evals: int, + last_error: str | None, +) -> str: + reasons = { + "convergence_decrement_tol": ( + "The decrement is below convergence_decrement_tol." + ), + "convergence_ftol_abs": ( + "The last step improved the objective by less than convergence_ftol_abs." + ), + "convergence_xtol_rel": "The relative step is below convergence_xtol_rel.", + "stopping_maxiter": "The maximum number of iterations was reached.", + "stopping_maxfun": ("The maximum number of function evaluations was reached."), + "line_search_failure": ( + "The line search found no point with a sufficiently better objective. " + "Possible reasons are inaccurate derivatives, an objective that is not " + "smooth, or a stopping tolerance below the attainable accuracy." + ), + } + msg = ( + f"{reasons[stop_reason]} The decrement g'(J'J)^-1 g is {decrement:.3g}, " + f"convergence_decrement_tol is {decrement_tol:.3g}. For a likelihood, the " + f"estimate is about {np.sqrt(decrement):.2g} robust standard errors away from " + "a stationary point." + ) + if stop_reason != "convergence_decrement_tol" and rank(factorization) < len( + factorization.gradient + ): + msg += " The outer product of gradients is singular; see the warning." + if n_failed_evals > 0: + msg += ( + f" At {n_failed_evals} trial points, the objective or its derivative " + "raised an error or was not finite. These points were rejected. The last " + f"error was: {last_error}" + ) + return msg + + +def _zero_columns_message(positions: NDArray[np.int64]) -> str: + return ( + "The derivatives of all likelihood contributions with respect to the internal " + f"parameters at positions {positions.tolist()} are zero at the start values. " + "These parameters do not affect the objective there, and BHHH does not move " + "them as long as this is the case. Check whether they are identified and " + "whether the start values are at a point where the derivative vanishes for " + "all observations, e.g. a standard deviation of a random effect of zero. " + + _POSITIONS_NOTE + ) + + +def _identification_message( + weak_directions: list[NDArray[np.int64]], n_obs: int, n_params: int +) -> str: + msg = ( + "The outer product of gradients (OPG) is singular or nearly singular at the " + "final parameters, so not all parameters are identified from the data. " + ) + if n_obs < n_params: + msg += ( + f"There are fewer likelihood contributions ({n_obs}) than parameters " + f"({n_params}). " + ) + if weak_directions: + groups = "; ".join(str(d.tolist()) for d in weak_directions) + msg += ( + "The following groups of internal parameters (by position) are involved " + f"in nearly singular directions: {groups}. " + ) + msg += ( + "This usually indicates collinear variables, perfect prediction or " + "parameters that do not affect the likelihood. Standard errors of the " + "involved parameters are not reliable. " + _POSITIONS_NOTE + ) + return msg + + +_POSITIONS_NOTE = ( + "Positions refer to the internal parameter vector, which equals the flattened " + "params if no constraints are used." +) diff --git a/src/optimagic/optimizers/_bhhh/linalg.py b/src/optimagic/optimizers/_bhhh/linalg.py new file mode 100644 index 000000000..1f9938f21 --- /dev/null +++ b/src/optimagic/optimizers/_bhhh/linalg.py @@ -0,0 +1,166 @@ +"""Linear algebra on the outer product of gradients (OPG) of the BHHH algorithm. + +The OPG B = J'J of the n x k Jacobian J of the contributions replaces the Hessian. All +operations work on the k x k matrix B, so their cost does not depend on n. + +Rank decisions are made on the OPG after scaling its columns to unit length (Jacobi +scaling with the column norms of J, as in MINPACK and TOMS 717), because thresholds +on the unscaled matrix depend on the units of the parameters. Small eigenvalues of the +scaled OPG are floored instead of truncated, which avoids minimizing in a subspace and +stopping short of the optimum (:cite:`Dennis1981`). + +""" + +from dataclasses import dataclass + +import numpy as np +from numpy.typing import NDArray + +WEAK_IDENTIFICATION_THRESHOLD = 1e-10 +"""Eigenvalues of the scaled OPG below this times the largest one are reported.""" + +LOADING_THRESHOLD = 0.1 +"""Parameters with an absolute eigenvector loading above this are reported.""" + + +@dataclass(frozen=True) +class OPGFactorization: + gradient: NDArray[np.float64] + """Gradient g = J'1 of the objective, shape (k,).""" + + scale: NDArray[np.float64] + """Column norms of the Jacobian with zeros replaced by one, shape (k,).""" + + eigenvalues: NDArray[np.float64] + """Eigenvalues of the scaled OPG in ascending order, shape (k,).""" + + eigenvectors: NDArray[np.float64] + """Orthonormal eigenvectors of the scaled OPG as columns, shape (k, k).""" + + floor: float + """Lower limit of the eigenvalues used in steps and decrements.""" + + zero_columns: NDArray[np.bool_] + """Whether a column of the Jacobian is zero, shape (k,).""" + + @property + def floored_eigenvalues(self) -> NDArray[np.float64]: + """Eigenvalues raised to the floor, shape (k,).""" + return np.maximum(self.eigenvalues, self.floor) + + @property + def scaled_gradient(self) -> NDArray[np.float64]: + """Gradient in scaled parameters, shape (k,).""" + return self.gradient / self.scale + + +def factorize_opg(jac: NDArray[np.float64]) -> OPGFactorization: + """Compute the eigendecomposition of the column-scaled OPG. + + Eigenvalues are floored at k * eps times the largest eigenvalue, which corresponds + to a condition number of the scaled Jacobian of about 1e7. + + Args: + jac: Jacobian of the contributions, shape (n, k). + + Returns: + The factorization of the OPG. + + """ + n_params = jac.shape[1] + gradient = jac.sum(axis=0) + opg = jac.T @ jac + norms = np.sqrt(np.diag(opg)) + zero_columns = norms == 0 + scale = np.where(zero_columns, 1.0, norms) + scaled_opg = opg / np.outer(scale, scale) + + # Zero columns are decoupled from the rest of the OPG. Decomposing the other block + # separately keeps rounding errors from moving the corresponding parameters. + nonzero = np.flatnonzero(~zero_columns) + block_values, block_vectors = np.linalg.eigh(scaled_opg[np.ix_(nonzero, nonzero)]) + eigenvalues = np.concatenate([np.zeros(zero_columns.sum()), block_values]) + eigenvectors = np.zeros((n_params, n_params)) + eigenvectors[np.flatnonzero(zero_columns), np.arange(zero_columns.sum())] = 1.0 + eigenvectors[np.ix_(nonzero, np.arange(zero_columns.sum(), n_params))] = ( + block_vectors + ) + order = np.argsort(eigenvalues, kind="stable") + eigenvalues, eigenvectors = eigenvalues[order], eigenvectors[:, order] + + largest = float(eigenvalues[-1]) + floor = n_params * np.finfo(float).eps * largest if largest > 0 else 1.0 + return OPGFactorization( + gradient=gradient, + scale=scale, + eigenvalues=eigenvalues, + eigenvectors=eigenvectors, + floor=floor, + zero_columns=zero_columns, + ) + + +def unconstrained_step( + factorization: OPGFactorization, +) -> tuple[NDArray[np.float64], float]: + """Compute the BHHH step -B⁻¹g and the decrement g'B⁻¹g. + + B is the OPG with floored eigenvalues. + + Args: + factorization: The factorization of the OPG. + + Returns: + - The step, shape (k,). + - The decrement. + + """ + v = factorization.eigenvectors + lam = factorization.floored_eigenvalues + projected = v.T @ factorization.scaled_gradient + scaled_step = -v @ (projected / lam) + step = scaled_step / factorization.scale + decrement = float(projected @ (projected / lam)) + return step, decrement + + +def rank(factorization: OPGFactorization) -> int: + """Return the numerical rank of the scaled OPG.""" + return int(np.sum(factorization.eigenvalues > factorization.floor)) + + +def condition_number(factorization: OPGFactorization) -> float: + """Return the condition number of the scaled OPG (inf if it is singular).""" + smallest = factorization.eigenvalues[0] + if smallest <= 0: + return np.inf + return float(factorization.eigenvalues[-1] / smallest) + + +def weakly_identified_directions( + factorization: OPGFactorization, +) -> list[NDArray[np.int64]]: + """Find the parameters involved in nearly singular directions of the scaled OPG. + + Args: + factorization: The factorization of the OPG. + + Returns: + One array per eigenvalue below WEAK_IDENTIFICATION_THRESHOLD times the largest + eigenvalue. Each array contains the positions of the parameters whose absolute + loading on the eigenvector exceeds LOADING_THRESHOLD, ordered by the absolute + loading. + + """ + largest = max(float(factorization.eigenvalues[-1]), 0.0) + threshold = WEAK_IDENTIFICATION_THRESHOLD * largest + out = [] + for value, vector in zip( + factorization.eigenvalues, factorization.eigenvectors.T, strict=True + ): + if value > threshold: + break + loadings = np.abs(vector) + involved = np.flatnonzero(loadings > LOADING_THRESHOLD) + out.append(involved[np.argsort(-loadings[involved])]) + return out diff --git a/src/optimagic/optimizers/_bhhh/line_search.py b/src/optimagic/optimizers/_bhhh/line_search.py new file mode 100644 index 000000000..5c42453a3 --- /dev/null +++ b/src/optimagic/optimizers/_bhhh/line_search.py @@ -0,0 +1,286 @@ +"""Line search of the BHHH algorithm. + +The line search backtracks with safeguarded quadratic and cubic interpolation until the +Armijo condition holds (:cite:`Dennis1996`, Algorithm A6.3.1). If the first trial step +is accepted, it can be doubled as long as the objective keeps improving, because the OPG +often overestimates the curvature far from the optimum or under misspecification +(:cite:`Train2009`, section 8.3). Only the objective is evaluated at trial points. Trial +points at which the objective is not finite or cannot be evaluated are rejected. + +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Annotated, Callable, Literal + +import numpy as np +import pydantic +from annotated_types import Ge, Gt, Lt +from numpy.typing import NDArray + +from optimagic.exceptions import InvalidAlgoOptionError, UserFunctionRuntimeError +from optimagic.optimization.algo_options import MAX_LINE_SEARCH_STEPS +from optimagic.typing import DEFAULT_PYDANTIC_CONFIG, PositiveInt, validated_dataclass + +MIN_SHRINK_FACTOR = 0.1 +"""Lower safeguard for interpolated step lengths and shrink factor at invalid points.""" + +MAX_SHRINK_FACTOR = 0.5 +"""Upper safeguard for interpolated step lengths.""" + + +def _line_search_error(e: pydantic.ValidationError) -> Exception: + msg = f"The following options of LineSearch are invalid:\n\n{e}" + return InvalidAlgoOptionError(msg) + + +@validated_dataclass(config=DEFAULT_PYDANTIC_CONFIG, make_error=_line_search_error) +@dataclass(frozen=True) +class LineSearch: + """Backtracking line search with the Armijo condition and optional step doubling. + + Trial points are only accepted if they improve the objective sufficiently. Steps + that are rejected are shortened by safeguarded quadratic and cubic interpolation + (:cite:`Dennis1996`, Algorithm A6.3.1). Trial points at which the objective is not + finite or raises an error are rejected and the step is shortened by a factor of 10. + + """ + + armijo_constant: Annotated[float, Gt(0), Lt(0.5)] = 1e-4 + r"""Constant c of the Armijo condition. + + A step length t is accepted if :math:`F(x + t p) \leq F(x) + c \, t \, g'p`, where + F is the objective, g its gradient and p the BHHH step. The default is the value + recommended by :cite:`Dennis1996`. + + """ + + max_backtracks: PositiveInt = MAX_LINE_SEARCH_STEPS + """Maximum number of step reductions per iteration. + + If no sufficient improvement is found, the optimization stops and reports a failure. + + """ + + expansion: Literal["doubling", "none"] = "doubling" + """How to lengthen a BHHH step that is accepted without backtracking. + + "doubling" tries step lengths 2, 4, 8, ... as long as the objective keeps improving + (:cite:`Train2009`, section 8.3). This makes BHHH much faster when the OPG + overestimates the curvature of the objective, which is common far from the optimum + and in misspecified models. It costs one additional evaluation of the objective + per iteration in which doubling does not pay off. "none" gives textbook BHHH with an + Armijo line search. + + """ + + max_step_factor: Annotated[float, Ge(1)] = 1024.0 + """Largest step length that expansion can reach, in multiples of the BHHH step. + + The default allows up to 10 doublings. Far from the optimum, the best step can be + several orders of magnitude longer than the BHHH step. With bounds, expansion also + stops at the first bound the step would cross. + + """ + + +@dataclass(frozen=True) +class LineSearchResult: + status: Literal["success", "max_backtracks", "max_fun_evals"] + """Whether a step was accepted, or which limit stopped the search.""" + + step_length: float + """Accepted step length t, or the last tried one if no step was accepted.""" + + x: NDArray[np.float64] + """Accepted parameters (or the start parameters if no step was accepted).""" + + fun_value: NDArray[np.float64] | None + """Contributions at the accepted parameters; None if no step was accepted.""" + + criterion: float + """Objective at the accepted parameters (or at the start parameters).""" + + n_fun_evals: int + """Number of evaluations of the objective.""" + + n_backtracks: int + """Number of step reductions.""" + + n_expansions: int + """Number of accepted step doublings.""" + + n_failed_fun_evals: int + """Number of evaluations of the objective that raised an error.""" + + last_error: UserFunctionRuntimeError | None + """The last error raised by an evaluation of the objective, if any.""" + + +def line_search( + fun: Callable[[NDArray[np.float64]], NDArray[np.float64]], + x: NDArray[np.float64], + criterion: float, + direction: NDArray[np.float64], + slope: float, + lower: NDArray[np.float64], + upper: NDArray[np.float64], + options: LineSearch, + initial_step_length: float, + max_step_length: float, + expand: bool, + max_backtracks: int, + max_fun_evals: int, +) -> LineSearchResult: + """Search for a step length along a descent direction. + + Args: + fun: Function that maps parameters of shape (k,) to contributions of shape + (n,) whose sum is minimized. It may raise a UserFunctionRuntimeError. + x: Current parameters, shape (k,). + criterion: Objective at x, i.e. the sum of the contributions. + direction: Descent direction, shape (k,). + slope: Directional derivative of the objective along direction (negative). + lower: Lower bounds on the parameters, shape (k,). Can contain -inf. + upper: Upper bounds on the parameters, shape (k,). Can contain inf. + options: Options of the line search. + initial_step_length: First step length to try. + max_step_length: Largest step length that expansion may reach. Must keep + x + max_step_length * direction within the bounds. + expand: Whether to expand a first step that is accepted. + max_backtracks: Maximum number of step reductions. + max_fun_evals: Maximum number of evaluations of fun. + + Returns: + The result of the line search. + + """ + n_fun_evals = 0 + n_backtracks = 0 + n_failed_fun_evals = 0 + last_error: UserFunctionRuntimeError | None = None + + def evaluate(t: float) -> tuple[NDArray[np.float64] | None, float]: + nonlocal n_fun_evals, n_failed_fun_evals, last_error + n_fun_evals += 1 + try: + values = fun(np.clip(x + t * direction, lower, upper)) + except UserFunctionRuntimeError as e: + n_failed_fun_evals += 1 + last_error = e + return None, np.nan + total = float(np.sum(values)) + return values, (total if np.isfinite(total) else np.nan) + + def is_acceptable(t: float, value: float) -> bool: + return bool(value <= criterion + options.armijo_constant * t * slope) + + def failure( + status: Literal["max_backtracks", "max_fun_evals"], t: float + ) -> LineSearchResult: + return LineSearchResult( + status=status, + step_length=t, + x=x, + fun_value=None, + criterion=criterion, + n_fun_evals=n_fun_evals, + n_backtracks=n_backtracks, + n_expansions=0, + n_failed_fun_evals=n_failed_fun_evals, + last_error=last_error, + ) + + t = initial_step_length + if max_fun_evals < 1: + return failure("max_fun_evals", t) + values, value = evaluate(t) + previous: tuple[float, float] | None = None + while not is_acceptable(t, value): + if n_backtracks >= max_backtracks: + return failure("max_backtracks", t) + if n_fun_evals >= max_fun_evals: + return failure("max_fun_evals", t) + t_new = next_step_length(t, value, previous, criterion, slope) + if np.isfinite(value): + previous = (t, value) + t = t_new + values, value = evaluate(t) + n_backtracks += 1 + + n_expansions = 0 + if expand and n_backtracks == 0 and options.expansion == "doubling": + while 2 * t <= max_step_length and n_fun_evals < max_fun_evals: + candidate_values, candidate = evaluate(2 * t) + if not candidate < value: + break + t, values, value = 2 * t, candidate_values, candidate + n_expansions += 1 + + return LineSearchResult( + status="success", + step_length=t, + x=np.clip(x + t * direction, lower, upper), + fun_value=values, + criterion=value, + n_fun_evals=n_fun_evals, + n_backtracks=n_backtracks, + n_expansions=n_expansions, + n_failed_fun_evals=n_failed_fun_evals, + last_error=last_error, + ) + + +def next_step_length( + t: float, + value: float, + previous: tuple[float, float] | None, + criterion: float, + slope: float, +) -> float: + """Compute the next trial step length after a rejected step. + + The first reduction minimizes the quadratic through the objective and its slope at + zero and the objective at t. Later reductions minimize the cubic that also passes + through the previous trial point (:cite:`Dennis1996`, Algorithm A6.3.1). The result + is safeguarded to lie in [0.1t, 0.5t]. If the objective is not finite at t, the + step length is reduced by a factor of 10. + + Args: + t: Rejected step length. + value: Objective at t; nan if it was not finite. + previous: The previous rejected step length and its objective value, if any + had a finite objective. + criterion: Objective at step length zero. + slope: Directional derivative of the objective at step length zero. + + Returns: + The next step length. + + """ + if not np.isfinite(value): + return MIN_SHRINK_FACTOR * t + + # numpy floats return inf or nan on overflow, where Python floats would raise + t, value, criterion, slope = map(np.float64, (t, value, criterion, slope)) + with np.errstate(all="ignore"): + excess = value - criterion - slope * t + if previous is None: + candidate = -slope * t**2 / (2 * excess) + else: + t_prev, value_prev = map(np.float64, previous) + excess_prev = value_prev - criterion - slope * t_prev + a = (excess / t**2 - excess_prev / t_prev**2) / (t - t_prev) + b = (-t_prev * excess / t**2 + t * excess_prev / t_prev**2) / (t - t_prev) + discriminant = b**2 - 3 * a * slope + if a == 0: + candidate = -slope / (2 * b) if b > 0 else np.nan + elif discriminant >= 0: + candidate = (-b + np.sqrt(discriminant)) / (3 * a) + else: + candidate = np.nan + + if not np.isfinite(candidate): + candidate = MAX_SHRINK_FACTOR * t + return float(np.clip(candidate, MIN_SHRINK_FACTOR * t, MAX_SHRINK_FACTOR * t)) diff --git a/src/optimagic/optimizers/_bhhh/subproblem.py b/src/optimagic/optimizers/_bhhh/subproblem.py new file mode 100644 index 000000000..2c0694673 --- /dev/null +++ b/src/optimagic/optimizers/_bhhh/subproblem.py @@ -0,0 +1,102 @@ +"""Step subproblem of the BHHH algorithm. + +Each iteration minimizes the quadratic model g'p + p'Bp / 2 of the objective, where g +is the gradient and B the OPG with floored eigenvalues. With bounds, the model is +minimized over the box of feasible steps, as in Bertsekas' projected Newton method +(:cite:`Bertsekas1982`) and the bounded variants of TOMS 717. Clipping or projecting +the unconstrained step instead can stall at non-optimal points. + +""" + +import numpy as np +from numpy.typing import NDArray +from scipy.optimize import lsq_linear + +from optimagic.optimizers._bhhh.linalg import OPGFactorization, unconstrained_step + + +def compute_step( + factorization: OPGFactorization, + lower: NDArray[np.float64], + upper: NDArray[np.float64], +) -> tuple[NDArray[np.float64], float]: + """Minimize the quadratic OPG model subject to bounds on the step. + + The decrement is twice the reduction of the model achieved by the step. Without + binding bounds it equals g'B⁻¹g. It is zero exactly at points that satisfy the + first order conditions of the bound constrained problem. + + Args: + factorization: The factorization of the OPG. + lower: Lower bounds on the step, shape (k,). Entries are non-positive and can + be -inf. + upper: Upper bounds on the step, shape (k,). Entries are non-negative and can + be inf. + + Returns: + - The step, shape (k,). + - The decrement. + + """ + step, decrement = unconstrained_step(factorization) + if np.all((step >= lower) & (step <= upper)): + return step, decrement + return _box_constrained_step(factorization, lower, upper) + + +def _box_constrained_step( + factorization: OPGFactorization, + lower: NDArray[np.float64], + upper: NDArray[np.float64], +) -> tuple[NDArray[np.float64], float]: + """Minimize the quadratic OPG model over a box with bounded-variable least squares. + + With the scaled step q = Dp and the factor A = Λ^(1/2)V' of the scaled OPG, the + model g'p + p'Bp / 2 equals ||Aq + c||² / 2 - ||c||² / 2 with c = Λ^(-1/2)V'D⁻¹g. + Working in scaled parameters keeps A well conditioned. + + """ + scale = factorization.scale + lam = factorization.floored_eigenvalues + v = factorization.eigenvectors + scaled_gradient = factorization.scaled_gradient + a = np.sqrt(lam)[:, None] * v.T + c = (v.T @ scaled_gradient) / np.sqrt(lam) + res = lsq_linear(a, -c, bounds=(lower * scale, upper * scale), method="bvls") + scaled_step = res.x + # Computing the decrease directly avoids cancellation between ||c||² and the + # residual sum of squares when the gradient pushes hard against a bound. + decrement = float( + -2 * scaled_gradient @ scaled_step - np.sum((a @ scaled_step) ** 2) + ) + step = np.clip(scaled_step / scale, lower, upper) + # Unscaling can move steps on a bound slightly into the interior. + step = np.where(res.active_mask == -1, lower, step) + step = np.where(res.active_mask == 1, upper, step) + return step, max(decrement, 0.0) + + +def max_feasible_step_length( + x: NDArray[np.float64], + direction: NDArray[np.float64], + lower: NDArray[np.float64], + upper: NDArray[np.float64], +) -> float: + """Return the largest t such that x + t * direction is within the bounds. + + Args: + x: Current parameters within the bounds, shape (k,). + direction: Search direction, shape (k,). + lower: Lower bounds on the parameters, shape (k,). Can contain -inf. + upper: Upper bounds on the parameters, shape (k,). Can contain inf. + + Returns: + The largest feasible step length; inf if the direction never leaves the box. + + """ + with np.errstate(divide="ignore", invalid="ignore"): + to_upper = np.where(direction > 0, (upper - x) / direction, np.inf) + to_lower = np.where(direction < 0, (lower - x) / direction, np.inf) + return float( + min(np.min(to_upper, initial=np.inf), np.min(to_lower, initial=np.inf)) + ) diff --git a/src/optimagic/optimizers/bhhh.py b/src/optimagic/optimizers/bhhh.py index c7e3a1539..57b6cde50 100644 --- a/src/optimagic/optimizers/bhhh.py +++ b/src/optimagic/optimizers/bhhh.py @@ -1,18 +1,30 @@ -"""Implement Berndt-Hall-Hall-Hausman (BHHH) algorithm.""" +"""Implement the Berndt-Hall-Hall-Hausman (BHHH) algorithm.""" + +from __future__ import annotations from dataclasses import dataclass -from typing import Callable, cast +from typing import Literal import numpy as np from numpy.typing import NDArray from optimagic import mark +from optimagic.optimization.algo_options import ( + CONVERGENCE_FTOL_ABS, + STOPPING_MAXFUN, + STOPPING_MAXITER, +) from optimagic.optimization.algorithm import Algorithm, InternalOptimizeResult from optimagic.optimization.internal_optimization_problem import ( InternalOptimizationProblem, ) +from optimagic.optimizers._bhhh.bhhh_loop import bhhh_internal +from optimagic.optimizers._bhhh.line_search import LineSearch from optimagic.typing import AggregationLevel, NonNegativeFloat, PositiveInt +CONVERGENCE_DECREMENT_TOL = 1e-8 +"""Default tolerance for the decrement; about 1e-4 robust standard errors.""" + @mark.minimizer( name="bhhh", @@ -23,116 +35,184 @@ needs_hess=False, needs_bounds=False, supports_parallelism=False, - supports_bounds=False, - supports_infinite_bounds=False, + supports_bounds=True, + supports_infinite_bounds=True, supports_linear_constraints=False, supports_nonlinear_constraints=False, disable_history=False, ) @dataclass(frozen=True) class BHHH(Algorithm): - converence_gtol_abs: NonNegativeFloat = 1e-8 - # TODO: Why is this 200? - stopping_maxiter: PositiveInt = 200 - - def _solve_internal_problem( - self, problem: InternalOptimizationProblem, x0: NDArray[np.float64] - ) -> InternalOptimizeResult: - res = bhhh_internal( - fun_and_jac=cast( - Callable[[NDArray[np.float64]], NDArray[np.float64]], - problem.fun_and_jac, - ), - x=x0, - gtol_abs=self.converence_gtol_abs, - maxiter=self.stopping_maxiter, - ) - - return res - + r"""Maximize a likelihood with the Berndt-Hall-Hall-Hausman (BHHH) algorithm. + + BHHH (:cite:`Berndt1974`) is a Newton-type method for maximum likelihood + estimation. It replaces the Hessian of the log-likelihood by the outer product of + gradients (OPG) of the likelihood contributions. By the information matrix equality + (:cite:`Halbert1982`), the OPG approximates the negative Hessian close to the + maximum of a correctly specified likelihood. BHHH only needs first derivatives of + the contributions, is invariant to linear reparametrizations of the parameters and + typically converges in a few dozen iterations. + + **How it works.** Internally, optimagic minimizes the sum of contributions + :math:`F(x) = \sum_i f_i(x)`, i.e. :math:`f_i = -\ell_i` when you maximize a + log-likelihood. Each iteration + + 1. evaluates the Jacobian :math:`J` (n x k) of the contributions at the current + parameters and forms the gradient :math:`g = J'1` and the OPG :math:`B = J'J`; + 2. computes the BHHH step :math:`p = -B^{-1} g`. With bounds, :math:`p` minimizes + the quadratic model :math:`g'p + p'Bp/2` over all feasible steps + (:cite:`Bertsekas1982`); + 3. chooses a step length along :math:`p` with a line search (see + :class:`~optimagic.optimizers.bhhh.LineSearch`). + + Only the objective is evaluated at trial points. The derivatives are evaluated + once per accepted point. + + Rank decisions use the OPG after scaling its diagonal to one. Eigenvalues of the + scaled OPG that are smaller than k times machine precision times the largest + eigenvalue are raised to that value instead of being dropped, which avoids + stopping short of the optimum when parameters are nearly collinear + (:cite:`Dennis1981`). + + **Stopping.** The algorithm stops successfully when the decrement + :math:`\delta = g'B^{-1}g` is below ``convergence_decrement_tol``. Unlike + criteria based on the gradient or on the change of the objective, the decrement + does not depend on the units of the parameters or on the number of observations. + For a likelihood, :math:`\sqrt{\delta}` approximates the distance to the maximum, + measured in robust (sandwich) standard errors, also in misspecified models. With + bounds, :math:`\delta` is twice the decrease of the quadratic model over the + feasible steps. It is zero exactly at points that satisfy the first order + conditions. The criteria ``convergence_ftol_abs`` and ``convergence_xtol_rel`` are + disabled by default. A run is reported as successful if any convergence criterion + is met. + + **Requirements on the objective function.** BHHH is only valid for log-likelihood + functions written as a sum of contributions. Decorate your function with + ``om.mark.likelihood`` and return one contribution per independent unit. The + algorithm cannot check most of the following requirements. Violating them makes + BHHH slow or makes it fail. + + - *Contributions of independent units.* The information matrix equality holds + per independent unit. If observations within a unit are dependent (e.g. panel + data with individual random effects), return one contribution per unit, i.e. + the sum over its observations. Conversely, do not aggregate independent + observations: with grouped or frequency data, pass one contribution per + observation, not per group. In the experiments of :cite:`Bunch1988`, grouping + made BHHH between 2 and about 20 times slower, and more so for larger groups. + - *Sum, do not average.* Do not divide the contributions by the number of + observations. Averaged contributions make the BHHH step n times too long. The + line search corrects this, but needs extra evaluations of the objective in each + iteration. + - *No weights.* For a weighted log-likelihood :math:`\sum_i w_i \ell_i`, the right + curvature estimate is :math:`\sum_i w_i s_i s_i'`, but the OPG of the weighted + contributions is :math:`\sum_i w_i^2 s_i s_i'`. With integer frequency weights, + repeat the observations instead. Other weights are not supported yet. + - *Only likelihoods.* For least-squares problems, GMM objectives or likelihoods + with a penalty added as an extra contribution, the information matrix equality + does not hold and BHHH is only a heuristic. optimagic accepts least-squares + problems for likelihood optimizers (the contributions are the squared + residuals), but you should use a least-squares optimizer for them. If the + residuals at the solution are small, the decrement does not go to zero and BHHH + cannot converge. + - *Identified parameters.* The OPG must be non-singular at the solution, so there + must be at least as many contributions as parameters. BHHH warns about + parameters that do not affect the objective at the start values and about a + nearly singular OPG at the solution. A parameter whose derivatives are zero for + all contributions is not moved by BHHH, e.g. the standard deviation of a random + coefficient that is started at zero. + - *Accurate derivatives.* The attainable decrement is limited by the accuracy of + the derivatives. Use closed form derivatives, automatic differentiation or + central finite differences (optimagic's default). + - *Finite start values.* The contributions and their derivatives must be finite + at the start values, and the functions must not raise errors there; otherwise + the optimization stops with an error. This catches most bugs in the objective + and derivative functions. Elsewhere, trial points at which the objective or its + derivatives are not finite or raise an error (e.g. outside the stationarity + region of a GARCH model) are rejected by the line search, whatever the value of + ``error_handling``. The number of rejected points is reported in + ``algorithm_output``, and the result message shows the last error. + + BHHH also converges for misspecified models, but more slowly, because the OPG no + longer approximates the Hessian. Bounds and constraints that optimagic implements + by reparametrization are supported; BHHH then works with the internal parameters. + + **Result.** ``jac`` is the gradient of the minimized objective with respect to the + internal parameters. No ``hess_inv`` is returned, because the inverse OPG is the + least reliable estimator of the covariance matrix; use + :func:`~optimagic.estimate_ml` instead. ``algorithm_output`` contains the final + decrement, the rank and condition number of the scaled OPG, the active bounds, the + numbers of step reductions, step expansions and failed evaluations of the + objective and the derivatives, and the reason for stopping. -def bhhh_internal( - fun_and_jac: Callable[[NDArray[np.float64]], NDArray[np.float64]], - x: NDArray[np.float64], - gtol_abs: NonNegativeFloat, - maxiter: PositiveInt, -) -> InternalOptimizeResult: - """Minimize a likelihood function using the BHHH algorithm. + """ - Args: - criterion_and_derivative: The objective function to be minimized. - x: Initial guess of the parameter vector (starting points). - convergence_absolute_gradient_tolerance: Stopping criterion for the - gradient tolerance. - stopping_max_iterations: Maximum number of iterations. If reached, - terminate. + globalization: Literal["line_search"] | LineSearch = "line_search" + """How the step length along the BHHH step is chosen. - Returns: - InternalOptimizeResult: The result of the optimization. + Currently, the only option is a line search. Pass "line_search" to use it with its + default options or a :class:`~optimagic.optimizers.bhhh.LineSearch` instance to + tune it, e.g. ``LineSearch(expansion="none")``. """ - criterion_accepted, gradient = fun_and_jac(x) - x_accepted = x - hessian_approx = np.dot(gradient.T, gradient) - gradient_sum = np.sum(gradient, axis=0) - direction = np.linalg.solve(hessian_approx, gradient_sum) - gtol = np.dot(gradient_sum, direction) + convergence_decrement_tol: NonNegativeFloat = CONVERGENCE_DECREMENT_TOL + r"""Stop successfully if the decrement is at most this. - initial_step_size = 1.0 - step_size = initial_step_size + The decrement is :math:`\delta = g'(J'J)^{-1}g`, where :math:`g` is the gradient and + :math:`J` the Jacobian of the contributions. For a likelihood, the estimate is then + about :math:`\sqrt{\delta}` robust standard errors away from the maximum. The + default of 1e-8 corresponds to 1e-4 standard errors. - niter = 1 - while niter < maxiter: - niter += 1 + """ - x_candidate = x_accepted + step_size * direction - criterion_candidate, gradient = fun_and_jac(x_candidate) + convergence_ftol_abs: NonNegativeFloat = CONVERGENCE_FTOL_ABS + """Stop if an accepted step improves the objective by at most this. - # If previous step was accepted - if step_size == initial_step_size: - hessian_approx = np.dot(gradient.T, gradient) + The objective is the sum of the contributions, so the tolerance is on the scale of + log-likelihood differences, whatever the number of observations. Set to zero (the + default) to disable the criterion. - else: - criterion_candidate, gradient = fun_and_jac(x_candidate) + """ - # Line search - if np.sum(criterion_candidate) > np.sum(criterion_accepted): - step_size /= 2 + convergence_xtol_rel: NonNegativeFloat = 0.0 + r"""Stop if the BHHH step is small relative to the parameters. - if step_size <= 0.01: - # Accept step - x_accepted = x_candidate - criterion_accepted = criterion_candidate + The criterion is :math:`\max_i |p_i| / \max(1, |x_i|) \leq` + ``convergence_xtol_rel``, where :math:`p` is the BHHH step before the line search + and :math:`x` are the current internal parameters. It depends on the units of the + parameters. Set to zero (the default) to disable the criterion. - # Reset step size - step_size = initial_step_size + """ - # If decrease in likelihood, calculate new direction vector - else: - # Accept step - x_accepted = x_candidate - criterion_accepted = criterion_candidate + stopping_maxiter: PositiveInt = STOPPING_MAXITER + """Maximum number of iterations, i.e. of accepted steps.""" - gradient_sum = np.sum(gradient, axis=0) - direction = np.linalg.solve(hessian_approx, gradient_sum) - gtol = np.dot(gradient_sum, direction) + stopping_maxfun: PositiveInt = STOPPING_MAXFUN + """Maximum number of evaluations of the objective. - if gtol < 0: - hessian_approx = np.dot(gradient.T, gradient) - direction = np.linalg.solve(hessian_approx, gradient_sum) + Evaluations of the derivatives are not counted. - # Reset stepsize - step_size = initial_step_size + """ - if gtol < gtol_abs: - break + def _solve_internal_problem( + self, problem: InternalOptimizationProblem, x0: NDArray[np.float64] + ) -> InternalOptimizeResult: + return bhhh_internal( + problem=problem, + x0=x0, + line_search_options=_resolve_globalization(self.globalization), + decrement_tol=self.convergence_decrement_tol, + ftol_abs=self.convergence_ftol_abs, + xtol_rel=self.convergence_xtol_rel, + maxiter=self.stopping_maxiter, + maxfun=self.stopping_maxfun, + ) - res = InternalOptimizeResult( - x=x_accepted, - fun=criterion_accepted, - message="Under development", - n_iterations=niter, - ) - return res +def _resolve_globalization( + globalization: Literal["line_search"] | LineSearch, +) -> LineSearch: + """Replace the name of a globalization strategy by its default instance.""" + if isinstance(globalization, str): + return LineSearch() + return globalization diff --git a/tests/optimagic/optimization/test_many_algorithms.py b/tests/optimagic/optimization/test_many_algorithms.py index 71a734069..4c6253344 100644 --- a/tests/optimagic/optimization/test_many_algorithms.py +++ b/tests/optimagic/optimization/test_many_algorithms.py @@ -20,6 +20,8 @@ from optimagic.optimization.optimize import minimize from optimagic.parameters.bounds import Bounds +# bhhh only converges on likelihoods, not on the zero-residual least-squares problem +# used here; it is tested in test_bhhh.py. AVAILABLE_LOCAL_ALGORITHMS = [ name for name, algo in AVAILABLE_ALGORITHMS.items() @@ -29,7 +31,7 @@ AVAILABLE_BOUNDED_ALGORITHMS = [ name for name, algo in AVAILABLE_ALGORITHMS.items() - if algo.algo_info.supports_bounds + if algo.algo_info.supports_bounds and name != "bhhh" ] PRECISION_LOOKUP = { diff --git a/tests/optimagic/optimizers/_bhhh/__init__.py b/tests/optimagic/optimizers/_bhhh/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/tests/optimagic/optimizers/_bhhh/test_linalg.py b/tests/optimagic/optimizers/_bhhh/test_linalg.py new file mode 100644 index 000000000..763b28b10 --- /dev/null +++ b/tests/optimagic/optimizers/_bhhh/test_linalg.py @@ -0,0 +1,127 @@ +import numpy as np +import pytest +from numpy.testing import assert_allclose + +from optimagic.optimizers._bhhh.linalg import ( + condition_number, + factorize_opg, + rank, + unconstrained_step, + weakly_identified_directions, +) +from optimagic.utilities import get_rng + + +def _random_jac(n_obs=200, n_params=4, seed=0): + rng = get_rng(seed) + scales = np.array([1e-3, 1, 10, 1e4])[:n_params] + return rng.normal(size=(n_obs, n_params)) * scales + 0.1 * scales + + +def test_factorization_reconstructs_opg(): + jac = _random_jac() + fact = factorize_opg(jac) + d, v, lam = fact.scale, fact.eigenvectors, fact.eigenvalues + reconstructed = np.outer(d, d) * (v @ np.diag(lam) @ v.T) + assert_allclose(fact.gradient, jac.sum(axis=0)) + assert_allclose(fact.scale, np.linalg.norm(jac, axis=0)) + assert_allclose(reconstructed, jac.T @ jac, rtol=1e-10) + assert not fact.zero_columns.any() + + +def test_unconstrained_step_matches_least_squares_solution(): + jac = _random_jac() + step, decrement = unconstrained_step(factorize_opg(jac)) + expected = -np.linalg.lstsq(jac, np.ones(len(jac)), rcond=None)[0] + assert_allclose(step, expected, rtol=1e-8) + assert_allclose(decrement, -jac.sum(axis=0) @ expected, rtol=1e-8) + + +def test_step_is_invariant_to_linear_reparametrization(): + # mixing columns of very different scale is ill-conditioned, so use unit scales + jac = _random_jac() + jac = jac / np.linalg.norm(jac, axis=0) + transform = get_rng(1).normal(size=(4, 4)) + 3 * np.eye(4) + step, decrement = unconstrained_step(factorize_opg(jac)) + new_step, new_decrement = unconstrained_step(factorize_opg(jac @ transform)) + assert_allclose(transform @ new_step, step, rtol=1e-7) + assert_allclose(new_decrement, decrement, rtol=1e-8) + + +def test_decrement_is_invariant_to_scaling_the_contributions(): + jac = _random_jac() + step, decrement = unconstrained_step(factorize_opg(jac)) + new_step, new_decrement = unconstrained_step(factorize_opg(1000 * jac)) + assert_allclose(new_decrement, decrement, rtol=1e-10) + assert_allclose(new_step, step / 1000, rtol=1e-10) + + +def test_zero_column(): + jac = _random_jac() + jac[:, 1] = 0 + fact = factorize_opg(jac) + step, decrement = unconstrained_step(fact) + assert fact.zero_columns.tolist() == [False, True, False, False] + assert fact.scale[1] == 1 + assert step[1] == 0 + assert np.isfinite(decrement) + assert rank(fact) == 3 + assert condition_number(fact) == np.inf + assert [d.tolist() for d in weakly_identified_directions(fact)] == [[1]] + + +def test_duplicated_column(): + jac = _random_jac() + jac[:, 3] = jac[:, 2] + fact = factorize_opg(jac) + step, _ = unconstrained_step(fact) + expected = -np.linalg.lstsq(jac, np.ones(len(jac)), rcond=None)[0] + assert np.all(np.isfinite(step)) + assert_allclose(jac @ step, jac @ expected, atol=1e-8) + assert rank(fact) == 3 + directions = weakly_identified_directions(fact) + assert len(directions) == 1 + assert sorted(directions[0].tolist()) == [2, 3] + + +def test_fewer_observations_than_parameters(): + jac = _random_jac(n_obs=2) + fact = factorize_opg(jac) + step, decrement = unconstrained_step(fact) + assert np.all(np.isfinite(step)) + assert rank(fact) == 2 + assert len(weakly_identified_directions(fact)) == 2 + # with two observations, the OPG regression fits the vector of ones exactly + assert_allclose(decrement, 2, rtol=1e-6) + + +def test_zero_jacobian(): + fact = factorize_opg(np.zeros((5, 3))) + step, decrement = unconstrained_step(fact) + assert_allclose(step, 0) + assert decrement == 0 + assert rank(fact) == 0 + + +@pytest.mark.parametrize("condition", [1e2, 1e4, 1e6]) +def test_ill_conditioned_jacobian(condition): + # the normal equations lose accuracy with the square of the condition number + rng = get_rng(2) + u, _ = np.linalg.qr(rng.normal(size=(500, 3))) + v, _ = np.linalg.qr(rng.normal(size=(3, 3))) + jac = u @ np.diag([1, 1 / np.sqrt(condition), 1 / condition]) @ v.T + step, decrement = unconstrained_step(factorize_opg(jac)) + expected = -np.linalg.lstsq(jac, np.ones(len(jac)), rcond=None)[0] + tol = 1e-13 * condition**2 + assert_allclose(jac @ step, jac @ expected, rtol=tol, atol=tol) + assert_allclose(decrement, -jac.sum(axis=0) @ expected, rtol=tol) + + +def test_condition_number_of_scaled_opg_ignores_units(): + jac = _random_jac() + unit_scaled = jac / np.linalg.norm(jac, axis=0) + assert_allclose( + condition_number(factorize_opg(jac)), + np.linalg.cond(unit_scaled.T @ unit_scaled), + rtol=1e-8, + ) diff --git a/tests/optimagic/optimizers/_bhhh/test_line_search.py b/tests/optimagic/optimizers/_bhhh/test_line_search.py new file mode 100644 index 000000000..ef52992bc --- /dev/null +++ b/tests/optimagic/optimizers/_bhhh/test_line_search.py @@ -0,0 +1,215 @@ +import numpy as np +import pytest +from numpy.testing import assert_allclose + +from optimagic.exceptions import InvalidAlgoOptionError, UserFunctionRuntimeError +from optimagic.optimizers._bhhh.line_search import ( + LineSearch, + line_search, + next_step_length, +) +from optimagic.utilities import get_rng + +INF = np.array([np.inf]) + + +def _quadratic(best_step_length): + """Contributions whose sum along direction -1 from x = 0 is minimal at t = best.""" + + def fun(x): + return np.array([(x[0] + best_step_length) ** 2, 0.0]) + + return fun + + +def _search( + fun, + options=None, + best_step_length=1.0, + max_step_length=np.inf, + expand=True, + max_backtracks=20, + max_fun_evals=1000, +): + """Search from x = 0 along direction -1.""" + x = np.zeros(1) + return line_search( + fun=fun, + x=x, + criterion=float(np.sum(fun(x))), + direction=-np.ones(1), + # the derivative of (x + a)² at 0 is 2a, along direction -1 it is -2a + slope=-2 * best_step_length, + lower=-INF, + upper=INF, + options=LineSearch() if options is None else options, + initial_step_length=1.0, + max_step_length=max_step_length, + expand=expand, + max_backtracks=max_backtracks, + max_fun_evals=max_fun_evals, + ) + + +def test_accepts_unit_step_if_it_is_optimal(): + res = _search(_quadratic(1.0), best_step_length=1.0) + assert res.status == "success" + assert res.step_length == 1 + assert res.n_backtracks == 0 + assert res.n_expansions == 0 + # one evaluation at t = 1 and one rejected doubling + assert res.n_fun_evals == 2 + + +def test_doubling_until_no_improvement(): + res = _search(_quadratic(10.0), best_step_length=10.0) + assert res.step_length == 8 + assert res.n_expansions == 3 + assert_allclose(res.x, [-8.0]) + assert_allclose(res.criterion, 4.0) + assert_allclose(res.fun_value, [4.0, 0.0]) + + +def test_doubling_respects_max_step_length(): + res = _search(_quadratic(10.0), best_step_length=10.0, max_step_length=5.0) + assert res.step_length == 4 + + +def test_no_doubling_with_expansion_none(): + res = _search( + _quadratic(10.0), options=LineSearch(expansion="none"), best_step_length=10.0 + ) + assert res.step_length == 1 + + +def test_no_doubling_if_expand_is_false(): + res = _search(_quadratic(10.0), best_step_length=10.0, expand=False) + assert res.step_length == 1 + + +def test_backtracking_satisfies_armijo_condition(): + # the unit step overshoots by a factor of 10 + res = _search(_quadratic(0.1), best_step_length=0.1) + assert res.status == "success" + assert res.n_backtracks >= 1 + assert res.n_expansions == 0 + armijo_bound = 0.01 + 1e-4 * res.step_length * (-0.2) + assert res.criterion <= armijo_bound + + +def test_non_finite_trial_points_are_rejected(): + def fun(x): + out = (x + 1) ** 2 + return np.where(x < -0.05, np.nan, out) + + res = _search(fun, best_step_length=1.0) + assert res.status == "success" + assert res.step_length <= 0.05 + assert np.isfinite(res.criterion) + + +def test_infinite_trial_points_are_rejected(): + def fun(x): + return np.where(x < -0.5, np.inf, (x + 1) ** 2) + + res = _search(fun, best_step_length=1.0) + assert res.status == "success" + assert res.step_length <= 0.5 + + +def test_trial_points_that_raise_are_rejected(): + def fun(x): + if x[0] < -0.5: + raise UserFunctionRuntimeError("Evaluation failed.") + return (x + 1) ** 2 + + res = _search(fun, best_step_length=1.0) + assert res.status == "success" + assert res.step_length <= 0.5 + assert res.n_failed_fun_evals == 1 + assert isinstance(res.last_error, UserFunctionRuntimeError) + + +def test_failure_after_max_backtracks(): + def fun(x): + return np.array([1.0 + abs(x[0])]) + + res = _search(fun, best_step_length=1.0, max_backtracks=5) + assert res.status == "max_backtracks" + assert res.n_backtracks == 5 + assert res.fun_value is None + assert_allclose(res.x, [0.0]) + + +def test_failure_if_budget_is_exhausted(): + def fun(x): + return np.array([1.0 + abs(x[0])]) + + res = _search(fun, best_step_length=1.0, max_fun_evals=3) + assert res.status == "max_fun_evals" + assert res.n_fun_evals == 3 + + +def test_no_evaluation_without_budget(): + res = _search(_quadratic(1.0), max_fun_evals=0) + assert res.status == "max_fun_evals" + assert res.n_fun_evals == 0 + + +def test_doubling_stops_when_budget_is_exhausted(): + res = _search(_quadratic(10.0), best_step_length=10.0, max_fun_evals=2) + assert res.status == "success" + assert res.step_length == 2 + + +def test_quadratic_interpolation_is_exact_for_quadratics(): + # f(t) = 1 - 2t + 5t² is minimal at t = 0.2; the rejected trial is t = 1 + t_new = next_step_length(t=1.0, value=4.0, previous=None, criterion=1.0, slope=-2) + assert_allclose(t_new, 0.2) + + +def test_cubic_interpolation_is_exact_for_cubics(): + def f(t): + return 1 - t + 2 * t**2 + 4 * t**3 + + # f'(t) = -1 + 4t + 12t² is zero at t = 1/6, which is within the safeguards + t_new = next_step_length( + t=0.5, value=f(0.5), previous=(1.0, f(1.0)), criterion=1.0, slope=-1.0 + ) + assert_allclose(t_new, 1 / 6) + + +def test_overflow_in_interpolation_falls_back_to_halving(): + t_new = next_step_length( + t=1e-200, value=1e300, previous=(1e-100, 1e300), criterion=0.0, slope=-1.0 + ) + assert t_new == 0.5e-200 + + +def test_non_finite_value_shrinks_step_by_factor_ten(): + assert next_step_length(1.0, np.nan, None, 1.0, -1.0) == 0.1 + + +@pytest.mark.parametrize("seed", range(20)) +def test_interpolated_step_lengths_are_safeguarded(seed): + rng = get_rng(seed) + t = rng.uniform(0.01, 1) + previous = (t * rng.uniform(2, 10), rng.uniform(-1, 10)) if seed % 2 else None + value = rng.uniform(-1, 10) + t_new = next_step_length(t, value, previous, criterion=0.0, slope=-rng.uniform()) + assert 0.1 * t <= t_new <= 0.5 * t + + +@pytest.mark.parametrize( + "kwargs", + [ + {"armijo_constant": 0.5}, + {"armijo_constant": 0}, + {"max_backtracks": 0}, + {"expansion": "quadratic"}, + {"max_step_factor": 0.5}, + ], +) +def test_invalid_options_raise(kwargs): + with pytest.raises(InvalidAlgoOptionError): + LineSearch(**kwargs) diff --git a/tests/optimagic/optimizers/_bhhh/test_subproblem.py b/tests/optimagic/optimizers/_bhhh/test_subproblem.py new file mode 100644 index 000000000..2107ddc8a --- /dev/null +++ b/tests/optimagic/optimizers/_bhhh/test_subproblem.py @@ -0,0 +1,95 @@ +import numpy as np +import pytest +from numpy.testing import assert_allclose +from scipy.optimize import minimize + +from optimagic.optimizers._bhhh.linalg import factorize_opg, unconstrained_step +from optimagic.optimizers._bhhh.subproblem import compute_step, max_feasible_step_length +from optimagic.utilities import get_rng + + +def _random_problem(seed, n_params=5): + rng = get_rng(seed) + jac = rng.normal(size=(50, n_params)) * rng.uniform(0.01, 100, size=n_params) + jac += 0.3 * rng.normal(size=n_params) + step, _ = unconstrained_step(factorize_opg(jac)) + # bounds that cut off a random subset of the unconstrained step + lower = -np.abs(step) * rng.uniform(0, 1.5, size=n_params) + upper = np.abs(step) * rng.uniform(0, 1.5, size=n_params) + lower[rng.uniform(size=n_params) < 0.3] = -np.inf + upper[rng.uniform(size=n_params) < 0.3] = np.inf + return jac, lower, upper + + +def test_unconstrained_step_is_returned_if_feasible(): + jac, _, _ = _random_problem(0) + fact = factorize_opg(jac) + inf = np.full(5, np.inf) + assert_allclose(compute_step(fact, -inf, inf)[0], unconstrained_step(fact)[0]) + assert compute_step(fact, -inf, inf)[1] == unconstrained_step(fact)[1] + + +@pytest.mark.parametrize("seed", range(10)) +def test_box_constrained_step_satisfies_kkt_conditions(seed): + jac, lower, upper = _random_problem(seed) + fact = factorize_opg(jac) + step, decrement = compute_step(fact, lower, upper) + gradient = jac.sum(axis=0) + opg = jac.T @ jac + model_gradient = (gradient + opg @ step) / fact.scale + + tol = 1e-6 * np.max(np.abs(gradient / fact.scale)) + at_lower = step <= lower + at_upper = step >= upper + free = ~at_lower & ~at_upper + assert np.all((step >= lower) & (step <= upper)) + assert_allclose(model_gradient[free], 0, atol=tol) + assert np.all(model_gradient[at_lower] >= -tol) + assert np.all(model_gradient[at_upper] <= tol) + model_decrease = -(gradient @ step + step @ opg @ step / 2) + assert_allclose(decrement, 2 * model_decrease, rtol=1e-6) + + +@pytest.mark.parametrize("seed", range(5)) +def test_box_constrained_step_matches_lbfgsb(seed): + jac, lower, upper = _random_problem(seed) + fact = factorize_opg(jac) + step, _ = compute_step(fact, lower, upper) + + # solve the same quadratic in scaled variables + gradient = jac.sum(axis=0) / fact.scale + hessian = jac.T @ jac / np.outer(fact.scale, fact.scale) + res = minimize( + lambda q: (gradient @ q + q @ hessian @ q / 2, gradient + hessian @ q), + x0=np.zeros(5), + jac=True, + method="L-BFGS-B", + bounds=list(zip(lower * fact.scale, upper * fact.scale, strict=True)), + options={"ftol": 1e-15, "gtol": 1e-12, "maxiter": 10_000}, + ) + assert_allclose(step * fact.scale, res.x, atol=1e-5) + + +def test_step_is_zero_at_bound_constrained_optimum(): + # the gradient pushes the first parameter against its lower bound + jac = np.array([[1.0, 0.5], [2.0, -0.5], [0.5, 0.0]]) + fact = factorize_opg(jac) + lower = np.array([0.0, -np.inf]) + upper = np.array([np.inf, np.inf]) + step, decrement = compute_step(fact, lower, upper) + assert step[0] == 0 + assert_allclose(decrement, 0, atol=1e-12) + + +def test_max_feasible_step_length(): + x = np.array([0.0, 1.0, 2.0]) + direction = np.array([1.0, -2.0, 0.0]) + lower = np.array([-1.0, 0.0, -np.inf]) + upper = np.array([4.0, 3.0, np.inf]) + assert max_feasible_step_length(x, direction, lower, upper) == 0.5 + + +def test_max_feasible_step_length_without_bounds(): + x = np.zeros(2) + inf = np.full(2, np.inf) + assert max_feasible_step_length(x, np.ones(2), -inf, inf) == np.inf diff --git a/tests/optimagic/optimizers/test_bhhh.py b/tests/optimagic/optimizers/test_bhhh.py index 14bdd0f31..8aa22c2e1 100644 --- a/tests/optimagic/optimizers/test_bhhh.py +++ b/tests/optimagic/optimizers/test_bhhh.py @@ -1,162 +1,584 @@ -"""Test the internal BHHH algorithm.""" +"""Test the BHHH algorithm end to end.""" -from functools import partial +import warnings +from dataclasses import dataclass +from typing import Any, Callable import numpy as np import pytest -import statsmodels.api as sm from numpy.testing import assert_array_almost_equal as aaae -from scipy.stats import norm +from scipy.special import expit -from optimagic import mark, minimize -from optimagic.optimizers.bhhh import bhhh_internal +import optimagic as om +from optimagic import mark +from optimagic.benchmarking.likelihood.problems import ( + LIKELIHOOD_SETS, + get_likelihood_problems, +) +from optimagic.benchmarking.likelihood.solutions import LIKELIHOOD_SOLUTIONS +from optimagic.exceptions import ( + InvalidAlgoOptionError, + InvalidFunctionError, + OptimagicError, +) +from optimagic.optimizers.bhhh import BHHH, LineSearch from optimagic.utilities import get_rng +# ====================================================================================== +# Helpers +# ====================================================================================== + + +@dataclass(frozen=True) +class BenchmarkProblem: + fun: Callable[..., Any] + jac: Callable[..., Any] + params: np.ndarray + bounds: om.Bounds | None + solution_x: np.ndarray + solution_fun: float + + +@dataclass(frozen=True) +class Logit: + fun: Callable[..., Any] + jac: Callable[..., Any] + gradient: Callable[..., Any] + solution: np.ndarray + + +def _get_benchmark_problem(set_name, instance_name, start): + instance = next(i for i in LIKELIHOOD_SETS[set_name] if i.name == instance_name) + likelihood = instance.build() + solution = LIKELIHOOD_SOLUTIONS[instance_name] + bounds = None + if likelihood.lower_bounds is not None or likelihood.upper_bounds is not None: + bounds = om.Bounds(lower=likelihood.lower_bounds, upper=likelihood.upper_bounds) + return BenchmarkProblem( + fun=mark.likelihood(likelihood.fun), + jac=mark.likelihood(likelihood.jac), + params=likelihood.good_start if start == "good" else likelihood.bad_start, + bounds=bounds, + solution_x=np.array(solution["params"]), + solution_fun=solution["value"], + ) + + +def _info(res: om.OptimizeResult) -> dict[str, Any]: + assert res.algorithm_output is not None + return res.algorithm_output + + +def _n_iterations(res: om.OptimizeResult) -> int: + assert res.n_iterations is not None + return res.n_iterations + + +def _logit_data(n_obs=500, seed=0): + rng = get_rng(seed) + x = np.column_stack([np.ones(n_obs), rng.normal(size=(n_obs, 2))]) + y = rng.uniform(size=n_obs) < expit(x @ np.array([0.5, 1.0, -1.0])) + return x, y + + +def _get_logit(x, y): + """Return log-likelihood contributions of a logit and their Jacobian.""" + + @mark.likelihood + def loglike(params): + index = x @ params + return y * index - np.logaddexp(0, index) + + @mark.likelihood + def loglike_jac(params): + return (y - expit(x @ params))[:, None] * x + + return loglike, loglike_jac + + +@pytest.fixture +def logit(): + x, y = _logit_data() + loglike, loglike_jac = _get_logit(x, y) + + def gradient(params): + return loglike_jac(params).sum(axis=0) -def generate_test_data(): - rng = get_rng(seed=12) + reference = om.maximize( + fun=loglike, + jac=gradient, + params=np.zeros(3), + algorithm="scipy_lbfgsb", + algo_options={"convergence_ftol_rel": 1e-15, "convergence_gtol_abs": 1e-12}, + ) + return Logit( + fun=loglike, jac=loglike_jac, gradient=gradient, solution=reference.params + ) - num_observations = 5000 - x1 = rng.multivariate_normal([0, 0], [[1, 0.75], [0.75, 1]], num_observations) - x2 = rng.multivariate_normal([1, 4], [[1, 0.75], [0.75, 1]], num_observations) - endog = np.hstack((np.zeros(num_observations), np.ones(num_observations))) +# ====================================================================================== +# Benchmark problems +# ====================================================================================== + +SMALL_GOOD_START = [ + "logit_5", + "logit_badly_scaled_8", + "probit_badly_scaled_6", + "poisson_5", + "negative_binomial_5", + "tobit_6", + "ordered_probit_8", + "multinomial_logit_11", + "weibull_5", + "gamma_regression_6", + "garch_3", + "garch_t_4", + "random_effects_probit_6", + "mixed_logit_zero_sd_8", + "stochastic_frontier_6", + "heckman_10", + "zero_inflated_poisson_8", + "fixed_effects_poisson_18", +] + +SMALL_BAD_START = [ + "logit_5", + "probit_badly_scaled_6", + "negative_binomial_5", + "multinomial_logit_11", + "garch_3", + "tobit_6", +] + +MISSPECIFIED = [ + "poisson_overdispersed_severe_5", + "poisson_underdispersed_severe_5", + "regression_t_errors_severe_5", + "logit_misclassified_severe_6", + "logit_sign_restricted_moderate_8", + "garch_t_innovations_severe_3", +] + +CASES = ( + [("likelihood_small", name, "good") for name in SMALL_GOOD_START] + + [("likelihood_small", name, "bad") for name in SMALL_BAD_START] + + [("likelihood_misspecified_small", name, "good") for name in MISSPECIFIED] + + [("likelihood_misspecified_small", name, "bad") for name in MISSPECIFIED] +) - simulated_exog = np.vstack((x1, x2)).astype(np.float32) - exog = simulated_exog - intercept = np.ones((exog.shape[0], 1)) - exog = np.hstack((intercept, exog)) - return endog, exog +@pytest.mark.parametrize("set_name, instance_name, start", CASES) +def test_bhhh_solves_benchmark_problem(set_name, instance_name, start): + problem = _get_benchmark_problem(set_name, instance_name, start) + res = om.minimize( + fun=problem.fun, + jac=problem.jac, + params=problem.params, + bounds=problem.bounds, + algorithm="bhhh", + ) + assert res.success + assert _info(res)["decrement"] <= 1e-8 + assert abs(res.fun - problem.solution_fun) < 1e-6 + aaae(res.params, problem.solution_x, decimal=3) -def _cdf_logit(x): - return 1 / (1 + np.exp(-x)) +def test_bhhh_with_active_bounds_at_solution(): + problem = _get_benchmark_problem( + "likelihood_misspecified_small", "logit_sign_restricted_moderate_8", "good" + ) + res = om.minimize( + fun=problem.fun, + jac=problem.jac, + params=problem.params, + bounds=problem.bounds, + algorithm="bhhh", + ) + active = _info(res)["active_lower_bounds"] + _info(res)["active_upper_bounds"] + assert res.success + assert len(active) > 0 -def get_loglikelihood_logit(endog, exog, x): - q = 2 * endog - 1 - linear_prediction = np.dot(exog, x) +# ====================================================================================== +# Interfaces and problem formulations +# ====================================================================================== - return np.log(_cdf_logit(q * linear_prediction)) +def test_maximize_log_likelihood(logit): + res = om.maximize( + fun=logit.fun, jac=logit.jac, params=np.zeros(3), algorithm="bhhh" + ) + assert res.success + aaae(res.params, logit.solution, decimal=5) -def get_score_logit(endog, exog, x): - linear_prediction = np.dot(exog, x) - return (endog - _cdf_logit(linear_prediction))[:, None] * exog +def test_numerical_derivatives(logit): + res = om.maximize(fun=logit.fun, params=np.zeros(3), algorithm="bhhh") + assert res.success + aaae(res.params, logit.solution, decimal=5) -def get_loglikelihood_probit(endog, exog, x): - q = 2 * endog - 1 - linear_prediction = np.dot(exog, x[: exog.shape[1]]) +def test_pytree_params_and_algorithm_instance(logit): + def fun(params): + return logit.fun(np.array([params["a"], *params["b"]])) + + res = om.maximize( + fun=mark.likelihood(fun), + params={"a": 0.0, "b": np.zeros(2)}, + algorithm=BHHH(globalization=LineSearch(expansion="none")), + ) + assert res.success + aaae(res.params["b"], logit.solution[1:], decimal=5) - return np.log(norm.cdf(q * linear_prediction)) +def test_bound_active_at_solution_matches_lbfgsb(logit): + bounds = om.Bounds(upper=np.array([np.inf, 0.7, np.inf])) + res = om.maximize( + fun=logit.fun, + jac=logit.jac, + params=np.zeros(3), + bounds=bounds, + algorithm="bhhh", + ) + expected = om.maximize( + fun=logit.fun, + jac=logit.gradient, + params=np.zeros(3), + bounds=bounds, + algorithm="scipy_lbfgsb", + algo_options={"convergence_ftol_rel": 1e-15, "convergence_gtol_abs": 1e-12}, + ) + assert res.success + assert res.params[1] == 0.7 + assert _info(res)["active_upper_bounds"] == [1] + aaae(res.params, expected.params, decimal=5) + + +def test_start_on_bound_that_is_active_at_solution(logit): + bounds = om.Bounds(lower=np.array([-np.inf, -np.inf, -0.5])) + res = om.maximize( + fun=logit.fun, + jac=logit.jac, + params=np.array([0.0, 0.0, -0.5]), + bounds=bounds, + algorithm="bhhh", + ) + assert res.success + assert res.params[2] == -0.5 -def get_score_probit(endog, exog, x): - q = 2 * endog - 1 - linear_prediction = np.dot(exog, x[: exog.shape[1]]) - derivative_loglikelihood = ( - q * norm.pdf(q * linear_prediction) / norm.cdf(q * linear_prediction) +def test_start_on_bound_that_is_inactive_at_solution(logit): + bounds = om.Bounds(lower=np.array([0.0, 0.0, -10.0])) + res = om.maximize( + fun=logit.fun, + jac=logit.jac, + params=np.array([0.0, 0.0, 0.0]), + bounds=bounds, + algorithm="bhhh", ) + assert res.success + aaae(res.params, logit.solution, decimal=5) - return derivative_loglikelihood[:, None] * exog +def test_non_finite_objective_at_trial_points_is_rejected(): + y = get_rng(0).normal(loc=1.0, size=200) -def criterion_and_derivative_logit(x): - """Return Logit criterion and derivative. + @mark.likelihood + def fun(params): + out = -((y - params[0]) ** 2) / 2 + return out if params[0] < 1.2 else np.full_like(y, np.nan) - Args: - x (np.ndarray): Parameter vector of shape (n_obs,). + res = om.maximize(fun=fun, params=np.zeros(1), algorithm="bhhh") + assert res.success + aaae(res.params, [y.mean()], decimal=5) - Returns: - tuple: first entry is the criterion, second entry is the score - """ - endog, exog = generate_test_data() - score = partial(get_score_logit, endog, exog) - loglike = partial(get_loglikelihood_logit, endog, exog) +@pytest.mark.parametrize("error_handling", ["raise", "continue"]) +def test_objective_that_raises_at_trial_points_is_rejected(error_handling): + y = get_rng(0).normal(loc=1.0, size=200) - return -loglike(x), score(x) + @mark.likelihood + def fun(params): + if params[0] >= 1.2: + raise ValueError("Objective failed.") + return -((y - params[0]) ** 2) / 2 + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + res = om.maximize( + fun=fun, + params=np.zeros(1), + algorithm="bhhh", + error_handling=error_handling, + ) + assert res.success + aaae(res.params, [y.mean()], decimal=5) + if error_handling == "raise": + assert _info(res)["n_failed_fun_evals"] > 0 + assert "ValueError: Objective failed." in str(res.message) -def criterion_and_derivative_probit(x): - """Return Probit criterion and derivative. - Args: - x (np.ndarray): Parameter vector of shape (n_obs,). +def test_non_finite_derivative_at_start_raises(logit): + @mark.likelihood + def jac(params): + return np.full_like(logit.jac(params), np.nan) - Returns: - tuple: first entry is the criterion, second entry is the score + with pytest.raises(OptimagicError, match="not finite|infinite or NaN"): + om.maximize(fun=logit.fun, jac=jac, params=np.zeros(3), algorithm="bhhh") - """ - endog, exog = generate_test_data() - score = partial(get_score_probit, endog, exog) - loglike = partial(get_loglikelihood_probit, endog, exog) +def test_failed_derivative_at_accepted_point_rejects_step(logit): + start = np.zeros(3) + failures = [] - return -loglike(x), score(x) + @mark.likelihood + def jac(params): + if not failures and not np.array_equal(params, start): + failures.append(params) + raise ValueError("Derivative failed.") + return logit.jac(params) + res = om.maximize(fun=logit.fun, jac=jac, params=start, algorithm="bhhh") + assert res.success + assert _info(res)["n_failed_jac_evals"] == 1 + aaae(res.params, logit.solution, decimal=5) -@pytest.fixture() -def result_statsmodels_logit(): - endog, exog = generate_test_data() - result = sm.Logit(endog, exog).fit() - return result +def test_derivative_that_always_fails_after_start_is_reported(logit): + start = np.zeros(3) + @mark.likelihood + def jac(params): + if not np.array_equal(params, start): + raise ValueError("Derivative failed.") + return logit.jac(params) -@pytest.fixture() -def result_statsmodels_probit(): - endog, exog = generate_test_data() - result = sm.Probit(endog, exog).fit() + res = om.maximize(fun=logit.fun, jac=jac, params=start, algorithm="bhhh") + assert not res.success + assert _info(res)["stop_reason"] == "line_search_failure" + assert "ValueError: Derivative failed." in str(res.message) - return result + +def test_wrong_derivative_is_reported_as_failure(logit): + @mark.likelihood + def wrong_jac(params): + return -logit.jac(params) + + res = om.maximize( + fun=logit.fun, jac=wrong_jac, params=np.zeros(3), algorithm="bhhh" + ) + assert not res.success + assert _info(res)["stop_reason"] == "line_search_failure" + assert "line search" in str(res.message) + + +def test_least_squares_problem_does_not_report_success(): + # For zero-residual least squares, the decrement does not converge to zero. + @mark.least_squares + def fun(params): + return params + + res = om.minimize( + fun=fun, + params=np.arange(1, 4, dtype=float), + algorithm=om.algos.bhhh(stopping_maxiter=30), + ) + assert not res.success + assert _info(res)["decrement"] > 1 + + +def test_scalar_objective_raises(): + with pytest.raises(InvalidFunctionError): + om.minimize(fun=lambda x: x @ x, params=np.ones(2), algorithm="bhhh") + + +# ====================================================================================== +# Stopping criteria and results +# ====================================================================================== + + +def test_result_fields(logit): + res = om.maximize( + fun=logit.fun, jac=logit.jac, params=np.zeros(3), algorithm="bhhh" + ) + info = _info(res) + assert np.asarray(res.jac).shape == (3,) + assert res.hess_inv is None + assert info["stop_reason"] == "convergence_decrement_tol" + assert info["rank"] == 3 + assert 1 <= info["condition_number"] < 10 + assert info["active_lower_bounds"] == info["active_upper_bounds"] == [] + n_iterations = _n_iterations(res) + assert n_iterations > 0 + assert res.n_jac_evals == n_iterations + 1 + assert res.n_fun_evals is not None + assert res.n_fun_evals >= n_iterations + 1 + assert "robust standard errors" in str(res.message) @pytest.mark.parametrize( - "criterion_and_derivative, result_statsmodels", + "options, stop_reason, n_iterations, success", [ - (criterion_and_derivative_logit, "result_statsmodels_logit"), - (criterion_and_derivative_probit, "result_statsmodels_probit"), + ({"stopping_maxiter": 1}, "stopping_maxiter", 1, False), + ({"stopping_maxfun": 1}, "stopping_maxfun", 0, False), + ({"convergence_ftol_abs": 1e10}, "convergence_ftol_abs", 1, True), + ({"convergence_xtol_rel": 1e10}, "convergence_xtol_rel", 0, True), ], ) -def test_maximum_likelihood(criterion_and_derivative, result_statsmodels, request): - result_expected = request.getfixturevalue(result_statsmodels) +def test_stopping_criteria(logit, options, stop_reason, n_iterations, success): + res = om.maximize( + fun=logit.fun, + jac=logit.jac, + params=np.zeros(3), + algorithm=om.algos.bhhh(**options), + ) + assert res.success is success + assert _info(res)["stop_reason"] == stop_reason + assert res.n_iterations == n_iterations - x = np.zeros(3) - result_bhhh = bhhh_internal( - criterion_and_derivative, - x=x, - gtol_abs=1e-8, - maxiter=200, +def test_large_decrement_tolerance_stops_at_start(logit): + res = om.maximize( + fun=logit.fun, + jac=logit.jac, + params=np.zeros(3), + algorithm=om.algos.bhhh().with_convergence(decrement_tol=1e10), ) + assert res.success + assert res.n_iterations == 0 + aaae(res.params, np.zeros(3)) + + +def test_tighter_decrement_tolerance_gets_closer(logit): + loose, tight = ( + om.maximize( + fun=logit.fun, + jac=logit.jac, + params=np.zeros(3), + algorithm=om.algos.bhhh(convergence_decrement_tol=tol), + ) + for tol in (1e-2, 1e-12) + ) + assert _info(loose)["decrement"] > 1e-12 + assert _info(tight)["decrement"] <= 1e-12 + assert tight.fun >= loose.fun + - aaae(result_bhhh.x, result_expected.params, decimal=4) +# ====================================================================================== +# Warnings about the problem formulation +# ====================================================================================== + + +def test_warns_about_parameter_without_effect(logit): + @mark.likelihood + def fun(params): + return logit.fun(params[:3]) + + with pytest.warns(UserWarning) as record: + res = om.maximize(fun=fun, params=np.zeros(4), algorithm="bhhh") + messages = [str(w.message) for w in record] + assert any("positions [3] are zero at the start" in m for m in messages) + assert any("nearly singular directions: [3]" in m for m in messages) + assert res.params[3] == 0 + aaae(res.params[:3], logit.solution, decimal=5) + + +def test_warns_about_collinear_parameters(): + x, y = _logit_data() + x = np.column_stack([x, x[:, 1]]) + loglike, loglike_jac = _get_logit(x, y) + with pytest.warns(UserWarning, match=r"nearly singular directions: \[[13], [13]\]"): + res = om.maximize( + fun=loglike, jac=loglike_jac, params=np.zeros(4), algorithm="bhhh" + ) + assert _info(res)["rank"] == 3 + + +def test_warns_about_fewer_observations_than_parameters(): + x, y = _logit_data(n_obs=2) + loglike, loglike_jac = _get_logit(x, y) + with pytest.warns(UserWarning, match="fewer likelihood contributions"): + om.maximize( + fun=loglike, + jac=loglike_jac, + params=np.zeros(3), + algorithm=om.algos.bhhh(stopping_maxiter=5), + ) + + +def test_no_warnings_for_well_posed_problem(logit): + with warnings.catch_warnings(): + warnings.simplefilter("error") + om.maximize(fun=logit.fun, jac=logit.jac, params=np.zeros(3), algorithm="bhhh") + + +# ====================================================================================== +# Options +# ====================================================================================== @pytest.mark.parametrize( - "criterion_and_derivative, result_statsmodels", + "options", [ - (criterion_and_derivative_logit, "result_statsmodels_logit"), - (criterion_and_derivative_probit, "result_statsmodels_probit"), + {"globalization": "trust_region"}, + {"convergence_decrement_tol": -1.0}, + {"stopping_maxiter": 0}, + {"converence_gtol_abs": 1e-8}, ], ) -def test_maximum_likelihood_external_interfaace( - criterion_and_derivative, result_statsmodels, request -): - result_expected = request.getfixturevalue(result_statsmodels) +def test_invalid_options_raise(options): + with pytest.raises(InvalidAlgoOptionError): + BHHH(**options) + + +def test_globalization_string_and_instance_are_equivalent(logit): + from_string, from_instance = ( + om.maximize( + fun=logit.fun, + jac=logit.jac, + params=np.zeros(3), + algorithm=BHHH(globalization=globalization), + ) + for globalization in ("line_search", LineSearch()) + ) + aaae(from_string.params, from_instance.params, decimal=12) + assert from_string.n_fun_evals == from_instance.n_fun_evals - x = np.zeros(3) - result_bhhh = minimize( - fun=mark.likelihood(criterion_and_derivative), - jac=True, - params=x, - algorithm="bhhh", - ) +# ====================================================================================== +# Regression guard on the likelihood benchmark +# ====================================================================================== + - aaae(result_bhhh.params, result_expected.params, decimal=4) +@pytest.mark.slow +@pytest.mark.parametrize( + "set_name, min_solved", + [("likelihood_small", 60), ("likelihood_misspecified_small", 69)], +) +def test_bhhh_on_likelihood_benchmark_set(set_name, min_solved): + # The failures are bad starts in regions where the OPG is a poor model (e.g. gamma + # and Weibull regressions). From the bad starts of the normal mixtures, BHHH + # converges to stationary points that are not the global optimum. + other_stationary_points = { + "normal_mixture_5_bad_start", + "normal_mixture_three_components_severe_5_bad_start", + } + problems = get_likelihood_problems(set_name) + n_solved = 0 + for name, problem in problems.items(): + bounds = om.Bounds(lower=problem["lower_bounds"], upper=problem["upper_bounds"]) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + res = om.minimize( + fun=problem["fun"], + jac=problem["jac"], + params=problem["start_x"], + bounds=bounds, + algorithm=om.algos.bhhh(stopping_maxfun=20_000), + ) + target = problem["solution_criterion"] + solved = abs(res.fun - target) <= 1e-5 * max(1, abs(target)) + if res.success and not solved: + assert name in other_stationary_points + n_solved += int(bool(res.success) and solved) + assert n_solved >= min_solved From d9a107d491c72046b17bcd415da6f3ebe9cedc7e Mon Sep 17 00:00:00 2001 From: Janos Gabler Date: Fri, 30 Oct 2026 09:14:09 +0100 Subject: [PATCH 2/3] Add changelog entry for #728 Co-Authored-By: Claude Opus 5.5 --- CHANGES.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CHANGES.md b/CHANGES.md index 9eb90421d..8f9618b63 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -10,6 +10,10 @@ releases are available on [Anaconda.org](https://anaconda.org/optimagic-dev/opti This release adds experimental support for **SciPy-style callbacks**, replaces pybaum by **optree** for pytree handling and uses **pydantic** to validate algorithm options. +- {gh}`728` Rewrites the `bhhh` optimizer. It now stops on the scale invariant decrement + `g'(J'J)^-1 g`, supports bounds, uses a line search with step doubling, rejects trial + points at which the objective or its derivative fails, and warns about weakly + identified parameters. The options of `bhhh` change ({ghuser}`janosg`). - {gh}`722` Adds four likelihood benchmark sets (`likelihood_small`, `likelihood_large`, `likelihood_misspecified_small`, `likelihood_misspecified_large`) with simulated data, closed form derivatives and bounds ({ghuser}`janosg`). From 2e790b6cddb1cf0f9ba42a3a45f31d13cd03b785 Mon Sep 17 00:00:00 2001 From: Janos Gabler Date: Wed, 25 Nov 2026 08:58:33 +0100 Subject: [PATCH 3/3] Fix the Windows test and docs build failures that came with the merge of main - tests/test_optimizer_library_markers.py (#749) read the source files with the platform encoding, which fails on Windows for the non-ASCII characters in the BHHH modules. Read them as UTF-8. - The LineSearch docs in algorithms.md and numdiff_background.md both cite Dennis1996, which sphinxcontrib-bibtex reports as a duplicate citation; since #741 the docs build fails on warnings. Prefix the keys of the local bibliography of numdiff_background.md. Co-Authored-By: Claude Opus 5.5 --- docs/source/explanation/numdiff_background.md | 9 +++++---- tests/test_optimizer_library_markers.py | 10 ++++++---- 2 files changed, 11 insertions(+), 8 deletions(-) diff --git a/docs/source/explanation/numdiff_background.md b/docs/source/explanation/numdiff_background.md index d9c368200..b1b3b9cdf 100644 --- a/docs/source/explanation/numdiff_background.md +++ b/docs/source/explanation/numdiff_background.md @@ -1,10 +1,10 @@ # Numerical differentiation: methods In this section we explain the mathematical background of forward, backward and central -differences. The main ideas in this chapter are taken from {cite}`Dennis1996`. x is used -for the pandas DataFrame with parameters. We index the entries of x as a n-dimensional -vector, where n is the number of variables in params_sr. The forward difference for the -gradient is given by: +differences. The main ideas in this chapter are taken from {cite}`nd-Dennis1996`. x is +used for the pandas DataFrame with parameters. We index the entries of x as a +n-dimensional vector, where n is the number of variables in params_sr. The forward +difference for the gradient is given by: $$ \nabla f(x) = \begin{pmatrix}\frac{f(x + e_0 * h_0) - f(x)}{h_0}\\ @@ -71,5 +71,6 @@ central differences. ```{eval-rst} .. bibliography:: ../refs.bib + :keyprefix: nd- :filter: docname in docnames ``` diff --git a/tests/test_optimizer_library_markers.py b/tests/test_optimizer_library_markers.py index 2ded31611..7df65f0d8 100644 --- a/tests/test_optimizer_library_markers.py +++ b/tests/test_optimizer_library_markers.py @@ -23,7 +23,7 @@ def test_every_optimizer_module_has_a_library_marker(): def test_every_library_marker_is_registered_and_has_a_pixi_environment(): - pyproject = tomllib.loads((ROOT / "pyproject.toml").read_text()) + pyproject = tomllib.loads((ROOT / "pyproject.toml").read_text(encoding="utf-8")) registered = { marker.split(":")[0] for marker in pyproject["tool"]["pytest"]["ini_options"]["markers"] @@ -34,7 +34,9 @@ def test_every_library_marker_is_registered_and_has_a_pixi_environment(): def test_every_library_marker_has_a_ci_job(): - workflow = yaml.safe_load((ROOT / ".github/workflows/main.yml").read_text()) + workflow = yaml.safe_load( + (ROOT / ".github/workflows/main.yml").read_text(encoding="utf-8") + ) job = workflow["jobs"]["run-optimizer-library-tests"] assert set(job["strategy"]["matrix"]["library"]) == LIBRARIES @@ -54,7 +56,7 @@ def test_tests_do_not_skip_on_missing_optimizer_libraries_themselves(): flags = _get_availability_flags_of_optimizer_modules() violations = [] for path in sorted((ROOT / "tests").rglob("*.py")): - tree = ast.parse(path.read_text()) + tree = ast.parse(path.read_text(encoding="utf-8")) allowed = _get_flag_nodes_that_guard_imports(tree, flags) violations += [ f"{path.relative_to(ROOT)}:{node.lineno}: {node.id}" @@ -68,7 +70,7 @@ def _get_availability_flags_of_optimizer_modules(): """Return the names of the flags that optimizer modules import from config.""" flags = set() for path in (ROOT / "src" / "optimagic" / "optimizers").rglob("*.py"): - for node in ast.walk(ast.parse(path.read_text())): + for node in ast.walk(ast.parse(path.read_text(encoding="utf-8"))): if isinstance(node, ast.ImportFrom) and node.module == "optimagic.config": flags |= {a.name for a in node.names if a.name.startswith("IS_")} return flags