diff --git a/.gitattributes b/.gitattributes index fb056aeb39a7faa551ef7696b0335ef72b4dc51d..71e80a48211eb6a88ad9b085c6275040ce898df1 100644 --- a/.gitattributes +++ b/.gitattributes @@ -349,3 +349,5 @@ llava_next/lib/python3.10/site-packages/scipy/stats/tests/__pycache__/test_mores llava_next/lib/python3.10/site-packages/scipy/stats/_rcont/rcont.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text llava_next/lib/python3.10/site-packages/scipy/stats/tests/__pycache__/test_stats.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text llava_next/lib/python3.10/site-packages/scipy/stats/__pycache__/_morestats.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text +llava_next/lib/python3.10/site-packages/scipy/cluster/__pycache__/hierarchy.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text +llava_next/lib/python3.10/site-packages/scipy/optimize/_moduleTNC.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text diff --git a/llava_next/lib/python3.10/site-packages/scipy/cluster/__pycache__/hierarchy.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/scipy/cluster/__pycache__/hierarchy.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..310ae1c3e67ca07767daaa7564c2bb3b9c0e91ec --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/scipy/cluster/__pycache__/hierarchy.cpython-310.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6c8ff3c6a3ffb2248f334cd8b237ecab483c6b6c57982eb950d95f3435bef174 +size 130979 diff --git a/llava_next/lib/python3.10/site-packages/scipy/linalg/tests/data/carex_20_data.npz b/llava_next/lib/python3.10/site-packages/scipy/linalg/tests/data/carex_20_data.npz new file mode 100644 index 0000000000000000000000000000000000000000..87266deb46238307347362b63a4878f2565baf56 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/scipy/linalg/tests/data/carex_20_data.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:14e222d34a7118c7284a1675c6feceee77b84df951a5c6ba2a5ee9ff3054fa1d +size 31231 diff --git a/llava_next/lib/python3.10/site-packages/scipy/optimize/README b/llava_next/lib/python3.10/site-packages/scipy/optimize/README new file mode 100644 index 0000000000000000000000000000000000000000..a355e0c447f2d36275877225fcbddd42f14636dd --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/scipy/optimize/README @@ -0,0 +1,76 @@ +From the website for the L-BFGS-B code (from at +http://www.ece.northwestern.edu/~nocedal/lbfgsb.html): + +""" +L-BFGS-B is a limited-memory quasi-Newton code for bound-constrained +optimization, i.e. for problems where the only constraints are of the +form l<= x <= u. +""" + +This is a Python wrapper (using F2PY) written by David M. Cooke + and released as version 0.9 on April 9, 2004. +The wrapper was slightly modified by Joonas Paalasmaa for the 3.0 version +in March 2012. + +License of L-BFGS-B (Fortran code) +================================== + +The version included here (in lbfgsb.f) is 3.0 (released April 25, 2011). It was +written by Ciyou Zhu, Richard Byrd, and Jorge Nocedal . It +carries the following condition for use: + + """ + This software is freely available, but we expect that all publications + describing work using this software, or all commercial products using it, + quote at least one of the references given below. This software is released + under the BSD License. + + References + * R. H. Byrd, P. Lu and J. Nocedal. A Limited Memory Algorithm for Bound + Constrained Optimization, (1995), SIAM Journal on Scientific and + Statistical Computing, 16, 5, pp. 1190-1208. + * C. Zhu, R. H. Byrd and J. Nocedal. L-BFGS-B: Algorithm 778: L-BFGS-B, + FORTRAN routines for large scale bound constrained optimization (1997), + ACM Transactions on Mathematical Software, 23, 4, pp. 550 - 560. + * J.L. Morales and J. Nocedal. L-BFGS-B: Remark on Algorithm 778: L-BFGS-B, + FORTRAN routines for large scale bound constrained optimization (2011), + ACM Transactions on Mathematical Software, 38, 1. + """ + +The Python wrapper +================== + +This code uses F2PY (http://cens.ioc.ee/projects/f2py2e/) to generate +the wrapper around the Fortran code. + +The Python code and wrapper are copyrighted 2004 by David M. Cooke +. + +Example usage +============= + +An example of the usage is given at the bottom of the lbfgsb.py file. +Run it with 'python lbfgsb.py'. + +License for the Python wrapper +============================== + +Copyright (c) 2004 David M. Cooke + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/llava_next/lib/python3.10/site-packages/scipy/optimize/__init__.py b/llava_next/lib/python3.10/site-packages/scipy/optimize/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d41cb5033af15131fa7d5a8ab490648553dc544b --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/scipy/optimize/__init__.py @@ -0,0 +1,452 @@ +""" +===================================================== +Optimization and root finding (:mod:`scipy.optimize`) +===================================================== + +.. currentmodule:: scipy.optimize + +.. toctree:: + :hidden: + + optimize.cython_optimize + +SciPy ``optimize`` provides functions for minimizing (or maximizing) +objective functions, possibly subject to constraints. It includes +solvers for nonlinear problems (with support for both local and global +optimization algorithms), linear programming, constrained +and nonlinear least-squares, root finding, and curve fitting. + +Common functions and objects, shared across different solvers, are: + +.. autosummary:: + :toctree: generated/ + + show_options - Show specific options optimization solvers. + OptimizeResult - The optimization result returned by some optimizers. + OptimizeWarning - The optimization encountered problems. + + +Optimization +============ + +Scalar functions optimization +----------------------------- + +.. autosummary:: + :toctree: generated/ + + minimize_scalar - Interface for minimizers of univariate functions + +The `minimize_scalar` function supports the following methods: + +.. toctree:: + + optimize.minimize_scalar-brent + optimize.minimize_scalar-bounded + optimize.minimize_scalar-golden + +Local (multivariate) optimization +--------------------------------- + +.. autosummary:: + :toctree: generated/ + + minimize - Interface for minimizers of multivariate functions. + +The `minimize` function supports the following methods: + +.. toctree:: + + optimize.minimize-neldermead + optimize.minimize-powell + optimize.minimize-cg + optimize.minimize-bfgs + optimize.minimize-newtoncg + optimize.minimize-lbfgsb + optimize.minimize-tnc + optimize.minimize-cobyla + optimize.minimize-cobyqa + optimize.minimize-slsqp + optimize.minimize-trustconstr + optimize.minimize-dogleg + optimize.minimize-trustncg + optimize.minimize-trustkrylov + optimize.minimize-trustexact + +Constraints are passed to `minimize` function as a single object or +as a list of objects from the following classes: + +.. autosummary:: + :toctree: generated/ + + NonlinearConstraint - Class defining general nonlinear constraints. + LinearConstraint - Class defining general linear constraints. + +Simple bound constraints are handled separately and there is a special class +for them: + +.. autosummary:: + :toctree: generated/ + + Bounds - Bound constraints. + +Quasi-Newton strategies implementing `HessianUpdateStrategy` +interface can be used to approximate the Hessian in `minimize` +function (available only for the 'trust-constr' method). Available +quasi-Newton methods implementing this interface are: + +.. autosummary:: + :toctree: generated/ + + BFGS - Broyden-Fletcher-Goldfarb-Shanno (BFGS) Hessian update strategy. + SR1 - Symmetric-rank-1 Hessian update strategy. + +.. _global_optimization: + +Global optimization +------------------- + +.. autosummary:: + :toctree: generated/ + + basinhopping - Basinhopping stochastic optimizer. + brute - Brute force searching optimizer. + differential_evolution - Stochastic optimizer using differential evolution. + + shgo - Simplicial homology global optimizer. + dual_annealing - Dual annealing stochastic optimizer. + direct - DIRECT (Dividing Rectangles) optimizer. + +Least-squares and curve fitting +=============================== + +Nonlinear least-squares +----------------------- + +.. autosummary:: + :toctree: generated/ + + least_squares - Solve a nonlinear least-squares problem with bounds on the variables. + +Linear least-squares +-------------------- + +.. autosummary:: + :toctree: generated/ + + nnls - Linear least-squares problem with non-negativity constraint. + lsq_linear - Linear least-squares problem with bound constraints. + isotonic_regression - Least squares problem of isotonic regression via PAVA. + +Curve fitting +------------- + +.. autosummary:: + :toctree: generated/ + + curve_fit -- Fit curve to a set of points. + +Root finding +============ + +Scalar functions +---------------- +.. autosummary:: + :toctree: generated/ + + root_scalar - Unified interface for nonlinear solvers of scalar functions. + brentq - quadratic interpolation Brent method. + brenth - Brent method, modified by Harris with hyperbolic extrapolation. + ridder - Ridder's method. + bisect - Bisection method. + newton - Newton's method (also Secant and Halley's methods). + toms748 - Alefeld, Potra & Shi Algorithm 748. + RootResults - The root finding result returned by some root finders. + +The `root_scalar` function supports the following methods: + +.. toctree:: + + optimize.root_scalar-brentq + optimize.root_scalar-brenth + optimize.root_scalar-bisect + optimize.root_scalar-ridder + optimize.root_scalar-newton + optimize.root_scalar-toms748 + optimize.root_scalar-secant + optimize.root_scalar-halley + + + +The table below lists situations and appropriate methods, along with +*asymptotic* convergence rates per iteration (and per function evaluation) +for successful convergence to a simple root(*). +Bisection is the slowest of them all, adding one bit of accuracy for each +function evaluation, but is guaranteed to converge. +The other bracketing methods all (eventually) increase the number of accurate +bits by about 50% for every function evaluation. +The derivative-based methods, all built on `newton`, can converge quite quickly +if the initial value is close to the root. They can also be applied to +functions defined on (a subset of) the complex plane. + ++-------------+----------+----------+-----------+-------------+-------------+----------------+ +| Domain of f | Bracket? | Derivatives? | Solvers | Convergence | ++ + +----------+-----------+ +-------------+----------------+ +| | | `fprime` | `fprime2` | | Guaranteed? | Rate(s)(*) | ++=============+==========+==========+===========+=============+=============+================+ +| `R` | Yes | N/A | N/A | - bisection | - Yes | - 1 "Linear" | +| | | | | - brentq | - Yes | - >=1, <= 1.62 | +| | | | | - brenth | - Yes | - >=1, <= 1.62 | +| | | | | - ridder | - Yes | - 2.0 (1.41) | +| | | | | - toms748 | - Yes | - 2.7 (1.65) | ++-------------+----------+----------+-----------+-------------+-------------+----------------+ +| `R` or `C` | No | No | No | secant | No | 1.62 (1.62) | ++-------------+----------+----------+-----------+-------------+-------------+----------------+ +| `R` or `C` | No | Yes | No | newton | No | 2.00 (1.41) | ++-------------+----------+----------+-----------+-------------+-------------+----------------+ +| `R` or `C` | No | Yes | Yes | halley | No | 3.00 (1.44) | ++-------------+----------+----------+-----------+-------------+-------------+----------------+ + +.. seealso:: + + `scipy.optimize.cython_optimize` -- Typed Cython versions of root finding functions + +Fixed point finding: + +.. autosummary:: + :toctree: generated/ + + fixed_point - Single-variable fixed-point solver. + +Multidimensional +---------------- + +.. autosummary:: + :toctree: generated/ + + root - Unified interface for nonlinear solvers of multivariate functions. + +The `root` function supports the following methods: + +.. toctree:: + + optimize.root-hybr + optimize.root-lm + optimize.root-broyden1 + optimize.root-broyden2 + optimize.root-anderson + optimize.root-linearmixing + optimize.root-diagbroyden + optimize.root-excitingmixing + optimize.root-krylov + optimize.root-dfsane + +Linear programming / MILP +========================= + +.. autosummary:: + :toctree: generated/ + + milp -- Mixed integer linear programming. + linprog -- Unified interface for minimizers of linear programming problems. + +The `linprog` function supports the following methods: + +.. toctree:: + + optimize.linprog-simplex + optimize.linprog-interior-point + optimize.linprog-revised_simplex + optimize.linprog-highs-ipm + optimize.linprog-highs-ds + optimize.linprog-highs + +The simplex, interior-point, and revised simplex methods support callback +functions, such as: + +.. autosummary:: + :toctree: generated/ + + linprog_verbose_callback -- Sample callback function for linprog (simplex). + +Assignment problems +=================== + +.. autosummary:: + :toctree: generated/ + + linear_sum_assignment -- Solves the linear-sum assignment problem. + quadratic_assignment -- Solves the quadratic assignment problem. + +The `quadratic_assignment` function supports the following methods: + +.. toctree:: + + optimize.qap-faq + optimize.qap-2opt + +Utilities +========= + +Finite-difference approximation +------------------------------- + +.. autosummary:: + :toctree: generated/ + + approx_fprime - Approximate the gradient of a scalar function. + check_grad - Check the supplied derivative using finite differences. + + +Line search +----------- + +.. autosummary:: + :toctree: generated/ + + bracket - Bracket a minimum, given two starting points. + line_search - Return a step that satisfies the strong Wolfe conditions. + +Hessian approximation +--------------------- + +.. autosummary:: + :toctree: generated/ + + LbfgsInvHessProduct - Linear operator for L-BFGS approximate inverse Hessian. + HessianUpdateStrategy - Interface for implementing Hessian update strategies + +Benchmark problems +------------------ + +.. autosummary:: + :toctree: generated/ + + rosen - The Rosenbrock function. + rosen_der - The derivative of the Rosenbrock function. + rosen_hess - The Hessian matrix of the Rosenbrock function. + rosen_hess_prod - Product of the Rosenbrock Hessian with a vector. + +Legacy functions +================ + +The functions below are not recommended for use in new scripts; +all of these methods are accessible via a newer, more consistent +interfaces, provided by the interfaces above. + +Optimization +------------ + +General-purpose multivariate methods: + +.. autosummary:: + :toctree: generated/ + + fmin - Nelder-Mead Simplex algorithm. + fmin_powell - Powell's (modified) conjugate direction method. + fmin_cg - Non-linear (Polak-Ribiere) conjugate gradient algorithm. + fmin_bfgs - Quasi-Newton method (Broydon-Fletcher-Goldfarb-Shanno). + fmin_ncg - Line-search Newton Conjugate Gradient. + +Constrained multivariate methods: + +.. autosummary:: + :toctree: generated/ + + fmin_l_bfgs_b - Zhu, Byrd, and Nocedal's constrained optimizer. + fmin_tnc - Truncated Newton code. + fmin_cobyla - Constrained optimization by linear approximation. + fmin_slsqp - Minimization using sequential least-squares programming. + +Univariate (scalar) minimization methods: + +.. autosummary:: + :toctree: generated/ + + fminbound - Bounded minimization of a scalar function. + brent - 1-D function minimization using Brent method. + golden - 1-D function minimization using Golden Section method. + +Least-squares +------------- + +.. autosummary:: + :toctree: generated/ + + leastsq - Minimize the sum of squares of M equations in N unknowns. + +Root finding +------------ + +General nonlinear solvers: + +.. autosummary:: + :toctree: generated/ + + fsolve - Non-linear multivariable equation solver. + broyden1 - Broyden's first method. + broyden2 - Broyden's second method. + NoConvergence - Exception raised when nonlinear solver does not converge. + +Large-scale nonlinear solvers: + +.. autosummary:: + :toctree: generated/ + + newton_krylov + anderson + + BroydenFirst + InverseJacobian + KrylovJacobian + +Simple iteration solvers: + +.. autosummary:: + :toctree: generated/ + + excitingmixing + linearmixing + diagbroyden + +""" # noqa: E501 + +from ._optimize import * +from ._minimize import * +from ._root import * +from ._root_scalar import * +from ._minpack_py import * +from ._zeros_py import * +from ._lbfgsb_py import fmin_l_bfgs_b, LbfgsInvHessProduct +from ._tnc import fmin_tnc +from ._cobyla_py import fmin_cobyla +from ._nonlin import * +from ._slsqp_py import fmin_slsqp +from ._nnls import nnls +from ._basinhopping import basinhopping +from ._linprog import linprog, linprog_verbose_callback +from ._lsap import linear_sum_assignment +from ._differentialevolution import differential_evolution +from ._lsq import least_squares, lsq_linear +from ._isotonic import isotonic_regression +from ._constraints import (NonlinearConstraint, + LinearConstraint, + Bounds) +from ._hessian_update_strategy import HessianUpdateStrategy, BFGS, SR1 +from ._shgo import shgo +from ._dual_annealing import dual_annealing +from ._qap import quadratic_assignment +from ._direct_py import direct +from ._milp import milp + +# Deprecated namespaces, to be removed in v2.0.0 +from . import ( + cobyla, lbfgsb, linesearch, minpack, minpack2, moduleTNC, nonlin, optimize, + slsqp, tnc, zeros +) + +__all__ = [s for s in dir() if not s.startswith('_')] + +from scipy._lib._testutils import PytestTester +test = PytestTester(__name__) +del PytestTester diff --git a/llava_next/lib/python3.10/site-packages/scipy/optimize/_bracket.py b/llava_next/lib/python3.10/site-packages/scipy/optimize/_bracket.py new file mode 100644 index 0000000000000000000000000000000000000000..6abfaaa94408ef2ec26b6932a023c6a8aa8ab6fd --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/scipy/optimize/_bracket.py @@ -0,0 +1,666 @@ +import numpy as np +import scipy._lib._elementwise_iterative_method as eim +from scipy._lib._util import _RichResult + +_ELIMITS = -1 # used in _bracket_root +_ESTOPONESIDE = 2 # used in _bracket_root + +def _bracket_root_iv(func, xl0, xr0, xmin, xmax, factor, args, maxiter): + + if not callable(func): + raise ValueError('`func` must be callable.') + + if not np.iterable(args): + args = (args,) + + xl0 = np.asarray(xl0)[()] + if not np.issubdtype(xl0.dtype, np.number) or np.iscomplex(xl0).any(): + raise ValueError('`xl0` must be numeric and real.') + + xr0 = xl0 + 1 if xr0 is None else xr0 + xmin = -np.inf if xmin is None else xmin + xmax = np.inf if xmax is None else xmax + factor = 2. if factor is None else factor + xl0, xr0, xmin, xmax, factor = np.broadcast_arrays(xl0, xr0, xmin, xmax, factor) + + if not np.issubdtype(xr0.dtype, np.number) or np.iscomplex(xr0).any(): + raise ValueError('`xr0` must be numeric and real.') + + if not np.issubdtype(xmin.dtype, np.number) or np.iscomplex(xmin).any(): + raise ValueError('`xmin` must be numeric and real.') + + if not np.issubdtype(xmax.dtype, np.number) or np.iscomplex(xmax).any(): + raise ValueError('`xmax` must be numeric and real.') + + if not np.issubdtype(factor.dtype, np.number) or np.iscomplex(factor).any(): + raise ValueError('`factor` must be numeric and real.') + if not np.all(factor > 1): + raise ValueError('All elements of `factor` must be greater than 1.') + + maxiter = np.asarray(maxiter) + message = '`maxiter` must be a non-negative integer.' + if (not np.issubdtype(maxiter.dtype, np.number) or maxiter.shape != tuple() + or np.iscomplex(maxiter)): + raise ValueError(message) + maxiter_int = int(maxiter[()]) + if not maxiter == maxiter_int or maxiter < 0: + raise ValueError(message) + + return func, xl0, xr0, xmin, xmax, factor, args, maxiter + + +def _bracket_root(func, xl0, xr0=None, *, xmin=None, xmax=None, factor=None, + args=(), maxiter=1000): + """Bracket the root of a monotonic scalar function of one variable + + This function works elementwise when `xl0`, `xr0`, `xmin`, `xmax`, `factor`, and + the elements of `args` are broadcastable arrays. + + Parameters + ---------- + func : callable + The function for which the root is to be bracketed. + The signature must be:: + + func(x: ndarray, *args) -> ndarray + + where each element of ``x`` is a finite real and ``args`` is a tuple, + which may contain an arbitrary number of arrays that are broadcastable + with `x`. ``func`` must be an elementwise function: each element + ``func(x)[i]`` must equal ``func(x[i])`` for all indices ``i``. + xl0, xr0: float array_like + Starting guess of bracket, which need not contain a root. If `xr0` is + not provided, ``xr0 = xl0 + 1``. Must be broadcastable with one another. + xmin, xmax : float array_like, optional + Minimum and maximum allowable endpoints of the bracket, inclusive. Must + be broadcastable with `xl0` and `xr0`. + factor : float array_like, default: 2 + The factor used to grow the bracket. See notes for details. + args : tuple, optional + Additional positional arguments to be passed to `func`. Must be arrays + broadcastable with `xl0`, `xr0`, `xmin`, and `xmax`. If the callable to be + bracketed requires arguments that are not broadcastable with these + arrays, wrap that callable with `func` such that `func` accepts + only `x` and broadcastable arrays. + maxiter : int, optional + The maximum number of iterations of the algorithm to perform. + + Returns + ------- + res : _RichResult + An instance of `scipy._lib._util._RichResult` with the following + attributes. The descriptions are written as though the values will be + scalars; however, if `func` returns an array, the outputs will be + arrays of the same shape. + + xl, xr : float + The lower and upper ends of the bracket, if the algorithm + terminated successfully. + fl, fr : float + The function value at the lower and upper ends of the bracket. + nfev : int + The number of function evaluations required to find the bracket. + This is distinct from the number of times `func` is *called* + because the function may evaluated at multiple points in a single + call. + nit : int + The number of iterations of the algorithm that were performed. + status : int + An integer representing the exit status of the algorithm. + + - ``0`` : The algorithm produced a valid bracket. + - ``-1`` : The bracket expanded to the allowable limits without finding a bracket. + - ``-2`` : The maximum number of iterations was reached. + - ``-3`` : A non-finite value was encountered. + - ``-4`` : Iteration was terminated by `callback`. + - ``-5``: The initial bracket does not satisfy `xmin <= xl0 < xr0 < xmax`. + - ``1`` : The algorithm is proceeding normally (in `callback` only). + - ``2`` : A bracket was found in the opposite search direction (in `callback` only). + + success : bool + ``True`` when the algorithm terminated successfully (status ``0``). + + Notes + ----- + This function generalizes an algorithm found in pieces throughout + `scipy.stats`. The strategy is to iteratively grow the bracket `(l, r)` + until ``func(l) < 0 < func(r)``. The bracket grows to the left as follows. + + - If `xmin` is not provided, the distance between `xl0` and `l` is iteratively + increased by `factor`. + - If `xmin` is provided, the distance between `xmin` and `l` is iteratively + decreased by `factor`. Note that this also *increases* the bracket size. + + Growth of the bracket to the right is analogous. + + Growth of the bracket in one direction stops when the endpoint is no longer + finite, the function value at the endpoint is no longer finite, or the + endpoint reaches its limiting value (`xmin` or `xmax`). Iteration terminates + when the bracket stops growing in both directions, the bracket surrounds + the root, or a root is found (accidentally). + + If two brackets are found - that is, a bracket is found on both sides in + the same iteration, the smaller of the two is returned. + If roots of the function are found, both `l` and `r` are set to the + leftmost root. + + """ # noqa: E501 + # Todo: + # - find bracket with sign change in specified direction + # - Add tolerance + # - allow factor < 1? + + callback = None # works; I just don't want to test it + temp = _bracket_root_iv(func, xl0, xr0, xmin, xmax, factor, args, maxiter) + func, xl0, xr0, xmin, xmax, factor, args, maxiter = temp + + xs = (xl0, xr0) + temp = eim._initialize(func, xs, args) + func, xs, fs, args, shape, dtype, xp = temp # line split for PEP8 + xl0, xr0 = xs + xmin = np.broadcast_to(xmin, shape).astype(dtype, copy=False).ravel() + xmax = np.broadcast_to(xmax, shape).astype(dtype, copy=False).ravel() + invalid_bracket = ~((xmin <= xl0) & (xl0 < xr0) & (xr0 <= xmax)) + + # The approach is to treat the left and right searches as though they were + # (almost) totally independent one-sided bracket searches. (The interaction + # is considered when checking for termination and preparing the result + # object.) + # `x` is the "moving" end of the bracket + x = np.concatenate(xs) + f = np.concatenate(fs) + invalid_bracket = np.concatenate((invalid_bracket, invalid_bracket)) + n = len(x) // 2 + + # `x_last` is the previous location of the moving end of the bracket. If + # the signs of `f` and `f_last` are different, `x` and `x_last` form a + # bracket. + x_last = np.concatenate((x[n:], x[:n])) + f_last = np.concatenate((f[n:], f[:n])) + # `x0` is the "fixed" end of the bracket. + x0 = x_last + # We don't need to retain the corresponding function value, since the + # fixed end of the bracket is only needed to compute the new value of the + # moving end; it is never returned. + limit = np.concatenate((xmin, xmax)) + + factor = np.broadcast_to(factor, shape).astype(dtype, copy=False).ravel() + factor = np.concatenate((factor, factor)) + + active = np.arange(2*n) + args = [np.concatenate((arg, arg)) for arg in args] + + # This is needed due to inner workings of `eim._loop`. + # We're abusing it a tiny bit. + shape = shape + (2,) + + # `d` is for "distance". + # For searches without a limit, the distance between the fixed end of the + # bracket `x0` and the moving end `x` will grow by `factor` each iteration. + # For searches with a limit, the distance between the `limit` and moving + # end of the bracket `x` will shrink by `factor` each iteration. + i = np.isinf(limit) + ni = ~i + d = np.zeros_like(x) + d[i] = x[i] - x0[i] + d[ni] = limit[ni] - x[ni] + + status = np.full_like(x, eim._EINPROGRESS, dtype=int) # in progress + status[invalid_bracket] = eim._EINPUTERR + nit, nfev = 0, 1 # one function evaluation per side performed above + + work = _RichResult(x=x, x0=x0, f=f, limit=limit, factor=factor, + active=active, d=d, x_last=x_last, f_last=f_last, + nit=nit, nfev=nfev, status=status, args=args, + xl=None, xr=None, fl=None, fr=None, n=n) + res_work_pairs = [('status', 'status'), ('xl', 'xl'), ('xr', 'xr'), + ('nit', 'nit'), ('nfev', 'nfev'), ('fl', 'fl'), + ('fr', 'fr'), ('x', 'x'), ('f', 'f'), + ('x_last', 'x_last'), ('f_last', 'f_last')] + + def pre_func_eval(work): + # Initialize moving end of bracket + x = np.zeros_like(work.x) + + # Unlimited brackets grow by `factor` by increasing distance from fixed + # end to moving end. + i = np.isinf(work.limit) # indices of unlimited brackets + work.d[i] *= work.factor[i] + x[i] = work.x0[i] + work.d[i] + + # Limited brackets grow by decreasing the distance from the limit to + # the moving end. + ni = ~i # indices of limited brackets + work.d[ni] /= work.factor[ni] + x[ni] = work.limit[ni] - work.d[ni] + + return x + + def post_func_eval(x, f, work): + # Keep track of the previous location of the moving end so that we can + # return a narrower bracket. (The alternative is to remember the + # original fixed end, but then the bracket would be wider than needed.) + work.x_last = work.x + work.f_last = work.f + work.x = x + work.f = f + + def check_termination(work): + # Condition 0: initial bracket is invalid + stop = (work.status == eim._EINPUTERR) + + # Condition 1: a valid bracket (or the root itself) has been found + sf = np.sign(work.f) + sf_last = np.sign(work.f_last) + i = ((sf_last == -sf) | (sf_last == 0) | (sf == 0)) & ~stop + work.status[i] = eim._ECONVERGED + stop[i] = True + + # Condition 2: the other side's search found a valid bracket. + # (If we just found a bracket with the rightward search, we can stop + # the leftward search, and vice-versa.) + # To do this, we need to set the status of the other side's search; + # this is tricky because `work.status` contains only the *active* + # elements, so we don't immediately know the index of the element we + # need to set - or even if it's still there. (That search may have + # terminated already, e.g. by reaching its `limit`.) + # To facilitate this, `work.active` contains a unit integer index of + # each search. Index `k` (`k < n)` and `k + n` correspond with a + # leftward and rightward search, respectively. Elements are removed + # from `work.active` just as they are removed from `work.status`, so + # we use `work.active` to help find the right location in + # `work.status`. + # Get the integer indices of the elements that can also stop + also_stop = (work.active[i] + work.n) % (2*work.n) + # Check whether they are still active. + # To start, we need to find out where in `work.active` they would + # appear if they are indeed there. + j = np.searchsorted(work.active, also_stop) + # If the location exceeds the length of the `work.active`, they are + # not there. + j = j[j < len(work.active)] + # Check whether they are still there. + j = j[also_stop == work.active[j]] + # Now convert these to boolean indices to use with `work.status`. + i = np.zeros_like(stop) + i[j] = True # boolean indices of elements that can also stop + i = i & ~stop + work.status[i] = _ESTOPONESIDE + stop[i] = True + + # Condition 3: moving end of bracket reaches limit + i = (work.x == work.limit) & ~stop + work.status[i] = _ELIMITS + stop[i] = True + + # Condition 4: non-finite value encountered + i = ~(np.isfinite(work.x) & np.isfinite(work.f)) & ~stop + work.status[i] = eim._EVALUEERR + stop[i] = True + + return stop + + def post_termination_check(work): + pass + + def customize_result(res, shape): + n = len(res['x']) // 2 + + # To avoid ambiguity, below we refer to `xl0`, the initial left endpoint + # as `a` and `xr0`, the initial right endpoint, as `b`. + # Because we treat the two one-sided searches as though they were + # independent, what we keep track of in `work` and what we want to + # return in `res` look quite different. Combine the results from the + # two one-sided searches before reporting the results to the user. + # - "a" refers to the leftward search (the moving end started at `a`) + # - "b" refers to the rightward search (the moving end started at `b`) + # - "l" refers to the left end of the bracket (closer to -oo) + # - "r" refers to the right end of the bracket (closer to +oo) + xal = res['x'][:n] + xar = res['x_last'][:n] + xbl = res['x_last'][n:] + xbr = res['x'][n:] + + fal = res['f'][:n] + far = res['f_last'][:n] + fbl = res['f_last'][n:] + fbr = res['f'][n:] + + # Initialize the brackets and corresponding function values to return + # to the user. Brackets may not be valid (e.g. there is no root, + # there weren't enough iterations, NaN encountered), but we still need + # to return something. One option would be all NaNs, but what I've + # chosen here is the left- and right-most points at which the function + # has been evaluated. This gives the user some information about what + # interval of the real line has been searched and shows that there is + # no sign change between the two ends. + xl = xal.copy() + fl = fal.copy() + xr = xbr.copy() + fr = fbr.copy() + + # `status` indicates whether the bracket is valid or not. If so, + # we want to adjust the bracket we return to be the narrowest possible + # given the points at which we evaluated the function. + # For example if bracket "a" is valid and smaller than bracket "b" OR + # if bracket "a" is valid and bracket "b" is not valid, we want to + # return bracket "a" (and vice versa). + sa = res['status'][:n] + sb = res['status'][n:] + + da = xar - xal + db = xbr - xbl + + i1 = ((da <= db) & (sa == 0)) | ((sa == 0) & (sb != 0)) + i2 = ((db <= da) & (sb == 0)) | ((sb == 0) & (sa != 0)) + + xr[i1] = xar[i1] + fr[i1] = far[i1] + xl[i2] = xbl[i2] + fl[i2] = fbl[i2] + + # Finish assembling the result object + res['xl'] = xl + res['xr'] = xr + res['fl'] = fl + res['fr'] = fr + + res['nit'] = np.maximum(res['nit'][:n], res['nit'][n:]) + res['nfev'] = res['nfev'][:n] + res['nfev'][n:] + # If the status on one side is zero, the status is zero. In any case, + # report the status from one side only. + res['status'] = np.choose(sa == 0, (sb, sa)) + res['success'] = (res['status'] == 0) + + del res['x'] + del res['f'] + del res['x_last'] + del res['f_last'] + + return shape[:-1] + + return eim._loop(work, callback, shape, maxiter, func, args, dtype, + pre_func_eval, post_func_eval, check_termination, + post_termination_check, customize_result, res_work_pairs, + xp) + + +def _bracket_minimum_iv(func, xm0, xl0, xr0, xmin, xmax, factor, args, maxiter): + + if not callable(func): + raise ValueError('`func` must be callable.') + + if not np.iterable(args): + args = (args,) + + xm0 = np.asarray(xm0)[()] + if not np.issubdtype(xm0.dtype, np.number) or np.iscomplex(xm0).any(): + raise ValueError('`xm0` must be numeric and real.') + + xmin = -np.inf if xmin is None else xmin + xmax = np.inf if xmax is None else xmax + + # If xl0 (xr0) is not supplied, fill with a dummy value for the sake + # of broadcasting. We need to wait until xmin (xmax) has been validated + # to compute the default values. + xl0_not_supplied = False + if xl0 is None: + xl0 = np.nan + xl0_not_supplied = True + + xr0_not_supplied = False + if xr0 is None: + xr0 = np.nan + xr0_not_supplied = True + + factor = 2.0 if factor is None else factor + xl0, xm0, xr0, xmin, xmax, factor = np.broadcast_arrays( + xl0, xm0, xr0, xmin, xmax, factor + ) + + if not np.issubdtype(xl0.dtype, np.number) or np.iscomplex(xl0).any(): + raise ValueError('`xl0` must be numeric and real.') + + if not np.issubdtype(xr0.dtype, np.number) or np.iscomplex(xr0).any(): + raise ValueError('`xr0` must be numeric and real.') + + if not np.issubdtype(xmin.dtype, np.number) or np.iscomplex(xmin).any(): + raise ValueError('`xmin` must be numeric and real.') + + if not np.issubdtype(xmax.dtype, np.number) or np.iscomplex(xmax).any(): + raise ValueError('`xmax` must be numeric and real.') + + if not np.issubdtype(factor.dtype, np.number) or np.iscomplex(factor).any(): + raise ValueError('`factor` must be numeric and real.') + if not np.all(factor > 1): + raise ValueError('All elements of `factor` must be greater than 1.') + + # Calculate default values of xl0 and/or xr0 if they have not been supplied + # by the user. We need to be careful to ensure xl0 and xr0 are not outside + # of (xmin, xmax). + if xl0_not_supplied: + xl0 = xm0 - np.minimum((xm0 - xmin)/16, 0.5) + if xr0_not_supplied: + xr0 = xm0 + np.minimum((xmax - xm0)/16, 0.5) + + maxiter = np.asarray(maxiter) + message = '`maxiter` must be a non-negative integer.' + if (not np.issubdtype(maxiter.dtype, np.number) or maxiter.shape != tuple() + or np.iscomplex(maxiter)): + raise ValueError(message) + maxiter_int = int(maxiter[()]) + if not maxiter == maxiter_int or maxiter < 0: + raise ValueError(message) + + return func, xm0, xl0, xr0, xmin, xmax, factor, args, maxiter + + +def _bracket_minimum(func, xm0, *, xl0=None, xr0=None, xmin=None, xmax=None, + factor=None, args=(), maxiter=1000): + """Bracket the minimum of a unimodal scalar function of one variable + + This function works elementwise when `xm0`, `xl0`, `xr0`, `xmin`, `xmax`, + and the elements of `args` are broadcastable arrays. + + Parameters + ---------- + func : callable + The function for which the minimum is to be bracketed. + The signature must be:: + + func(x: ndarray, *args) -> ndarray + + where each element of ``x`` is a finite real and ``args`` is a tuple, + which may contain an arbitrary number of arrays that are broadcastable + with ``x``. `func` must be an elementwise function: each element + ``func(x)[i]`` must equal ``func(x[i])`` for all indices `i`. + xm0: float array_like + Starting guess for middle point of bracket. + xl0, xr0: float array_like, optional + Starting guesses for left and right endpoints of the bracket. Must be + broadcastable with one another and with `xm0`. + xmin, xmax : float array_like, optional + Minimum and maximum allowable endpoints of the bracket, inclusive. Must + be broadcastable with `xl0`, `xm0`, and `xr0`. + factor : float array_like, optional + Controls expansion of bracket endpoint in downhill direction. Works + differently in the cases where a limit is set in the downhill direction + with `xmax` or `xmin`. See Notes. + args : tuple, optional + Additional positional arguments to be passed to `func`. Must be arrays + broadcastable with `xl0`, `xm0`, `xr0`, `xmin`, and `xmax`. If the + callable to be bracketed requires arguments that are not broadcastable + with these arrays, wrap that callable with `func` such that `func` + accepts only ``x`` and broadcastable arrays. + maxiter : int, optional + The maximum number of iterations of the algorithm to perform. The number + of function evaluations is three greater than the number of iterations. + + Returns + ------- + res : _RichResult + An instance of `scipy._lib._util._RichResult` with the following + attributes. The descriptions are written as though the values will be + scalars; however, if `func` returns an array, the outputs will be + arrays of the same shape. + + xl, xm, xr : float + The left, middle, and right points of the bracket, if the algorithm + terminated successfully. + fl, fm, fr : float + The function value at the left, middle, and right points of the bracket. + nfev : int + The number of function evaluations required to find the bracket. + nit : int + The number of iterations of the algorithm that were performed. + status : int + An integer representing the exit status of the algorithm. + + - ``0`` : The algorithm produced a valid bracket. + - ``-1`` : The bracket expanded to the allowable limits. Assuming + unimodality, this implies the endpoint at the limit is a + minimizer. + - ``-2`` : The maximum number of iterations was reached. + - ``-3`` : A non-finite value was encountered. + - ``-4`` : ``None`` shall pass. + - ``-5`` : The initial bracket does not satisfy + `xmin <= xl0 < xm0 < xr0 <= xmax`. + + success : bool + ``True`` when the algorithm terminated successfully (status ``0``). + + Notes + ----- + Similar to `scipy.optimize.bracket`, this function seeks to find real + points ``xl < xm < xr`` such that ``f(xl) >= f(xm)`` and ``f(xr) >= f(xm)``, + where at least one of the inequalities is strict. Unlike `scipy.optimize.bracket`, + this function can operate in a vectorized manner on array input, so long as + the input arrays are broadcastable with each other. Also unlike + `scipy.optimize.bracket`, users may specify minimum and maximum endpoints + for the desired bracket. + + Given an initial trio of points ``xl = xl0``, ``xm = xm0``, ``xr = xr0``, + the algorithm checks if these points already give a valid bracket. If not, + a new endpoint, ``w`` is chosen in the "downhill" direction, ``xm`` becomes the new + opposite endpoint, and either `xl` or `xr` becomes the new middle point, + depending on which direction is downhill. The algorithm repeats from here. + + The new endpoint `w` is chosen differently depending on whether or not a + boundary `xmin` or `xmax` has been set in the downhill direction. Without + loss of generality, suppose the downhill direction is to the right, so that + ``f(xl) > f(xm) > f(xr)``. If there is no boundary to the right, then `w` + is chosen to be ``xr + factor * (xr - xm)`` where `factor` is controlled by + the user (defaults to 2.0) so that step sizes increase in geometric proportion. + If there is a boundary, `xmax` in this case, then `w` is chosen to be + ``xmax - (xmax - xr)/factor``, with steps slowing to a stop at + `xmax`. This cautious approach ensures that a minimum near but distinct from + the boundary isn't missed while also detecting whether or not the `xmax` is + a minimizer when `xmax` is reached after a finite number of steps. + """ # noqa: E501 + callback = None # works; I just don't want to test it + + temp = _bracket_minimum_iv(func, xm0, xl0, xr0, xmin, xmax, factor, args, maxiter) + func, xm0, xl0, xr0, xmin, xmax, factor, args, maxiter = temp + + xs = (xl0, xm0, xr0) + temp = eim._initialize(func, xs, args) + func, xs, fs, args, shape, dtype, xp = temp + + xl0, xm0, xr0 = xs + fl0, fm0, fr0 = fs + xmin = np.broadcast_to(xmin, shape).astype(dtype, copy=False).ravel() + xmax = np.broadcast_to(xmax, shape).astype(dtype, copy=False).ravel() + invalid_bracket = ~((xmin <= xl0) & (xl0 < xm0) & (xm0 < xr0) & (xr0 <= xmax)) + # We will modify factor later on so make a copy. np.broadcast_to returns + # a read-only view. + factor = np.broadcast_to(factor, shape).astype(dtype, copy=True).ravel() + + # To simplify the logic, swap xl and xr if f(xl) < f(xr). We should always be + # marching downhill in the direction from xl to xr. + comp = fl0 < fr0 + xl0[comp], xr0[comp] = xr0[comp], xl0[comp] + fl0[comp], fr0[comp] = fr0[comp], fl0[comp] + # We only need the boundary in the direction we're traveling. + limit = np.where(comp, xmin, xmax) + + unlimited = np.isinf(limit) + limited = ~unlimited + step = np.empty_like(xl0) + + step[unlimited] = (xr0[unlimited] - xm0[unlimited]) + step[limited] = (limit[limited] - xr0[limited]) + + # Step size is divided by factor for case where there is a limit. + factor[limited] = 1 / factor[limited] + + status = np.full_like(xl0, eim._EINPROGRESS, dtype=int) + status[invalid_bracket] = eim._EINPUTERR + nit, nfev = 0, 3 + + work = _RichResult(xl=xl0, xm=xm0, xr=xr0, xr0=xr0, fl=fl0, fm=fm0, fr=fr0, + step=step, limit=limit, limited=limited, factor=factor, nit=nit, + nfev=nfev, status=status, args=args) + + res_work_pairs = [('status', 'status'), ('xl', 'xl'), ('xm', 'xm'), ('xr', 'xr'), + ('nit', 'nit'), ('nfev', 'nfev'), ('fl', 'fl'), ('fm', 'fm'), + ('fr', 'fr')] + + def pre_func_eval(work): + work.step *= work.factor + x = np.empty_like(work.xr) + x[~work.limited] = work.xr0[~work.limited] + work.step[~work.limited] + x[work.limited] = work.limit[work.limited] - work.step[work.limited] + # Since the new bracket endpoint is calculated from an offset with the + # limit, it may be the case that the new endpoint equals the old endpoint, + # when the old endpoint is sufficiently close to the limit. We use the + # limit itself as the new endpoint in these cases. + x[work.limited] = np.where( + x[work.limited] == work.xr[work.limited], + work.limit[work.limited], + x[work.limited], + ) + return x + + def post_func_eval(x, f, work): + work.xl, work.xm, work.xr = work.xm, work.xr, x + work.fl, work.fm, work.fr = work.fm, work.fr, f + + def check_termination(work): + # Condition 0: Initial bracket is invalid. + stop = (work.status == eim._EINPUTERR) + + # Condition 1: A valid bracket has been found. + i = ( + (work.fl >= work.fm) & (work.fr > work.fm) + | (work.fl > work.fm) & (work.fr >= work.fm) + ) & ~stop + work.status[i] = eim._ECONVERGED + stop[i] = True + + # Condition 2: Moving end of bracket reaches limit. + i = (work.xr == work.limit) & ~stop + work.status[i] = _ELIMITS + stop[i] = True + + # Condition 3: non-finite value encountered + i = ~(np.isfinite(work.xr) & np.isfinite(work.fr)) & ~stop + work.status[i] = eim._EVALUEERR + stop[i] = True + + return stop + + def post_termination_check(work): + pass + + def customize_result(res, shape): + # Reorder entries of xl and xr if they were swapped due to f(xl0) < f(xr0). + comp = res['xl'] > res['xr'] + res['xl'][comp], res['xr'][comp] = res['xr'][comp], res['xl'][comp] + res['fl'][comp], res['fr'][comp] = res['fr'][comp], res['fl'][comp] + return shape + + return eim._loop(work, callback, shape, + maxiter, func, args, dtype, + pre_func_eval, post_func_eval, + check_termination, post_termination_check, + customize_result, res_work_pairs, xp) diff --git a/llava_next/lib/python3.10/site-packages/scipy/optimize/_chandrupatla.py b/llava_next/lib/python3.10/site-packages/scipy/optimize/_chandrupatla.py new file mode 100644 index 0000000000000000000000000000000000000000..f1759d6191db209d26bbabc6ebc81a951b43b884 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/scipy/optimize/_chandrupatla.py @@ -0,0 +1,549 @@ +import math +import numpy as np +import scipy._lib._elementwise_iterative_method as eim +from scipy._lib._util import _RichResult +from scipy._lib._array_api import xp_clip, xp_minimum, xp_sign + +# TODO: +# - (maybe?) don't use fancy indexing assignment +# - figure out how to replace the new `try`/`except`s + + +def _chandrupatla(func, a, b, *, args=(), xatol=None, xrtol=None, + fatol=None, frtol=0, maxiter=None, callback=None): + """Find the root of an elementwise function using Chandrupatla's algorithm. + + For each element of the output of `func`, `chandrupatla` seeks the scalar + root that makes the element 0. This function allows for `a`, `b`, and the + output of `func` to be of any broadcastable shapes. + + Parameters + ---------- + func : callable + The function whose root is desired. The signature must be:: + + func(x: ndarray, *args) -> ndarray + + where each element of ``x`` is a finite real and ``args`` is a tuple, + which may contain an arbitrary number of components of any type(s). + ``func`` must be an elementwise function: each element ``func(x)[i]`` + must equal ``func(x[i])`` for all indices ``i``. `_chandrupatla` + seeks an array ``x`` such that ``func(x)`` is an array of zeros. + a, b : array_like + The lower and upper bounds of the root of the function. Must be + broadcastable with one another. + args : tuple, optional + Additional positional arguments to be passed to `func`. + xatol, xrtol, fatol, frtol : float, optional + Absolute and relative tolerances on the root and function value. + See Notes for details. + maxiter : int, optional + The maximum number of iterations of the algorithm to perform. + The default is the maximum possible number of bisections within + the (normal) floating point numbers of the relevant dtype. + callback : callable, optional + An optional user-supplied function to be called before the first + iteration and after each iteration. + Called as ``callback(res)``, where ``res`` is a ``_RichResult`` + similar to that returned by `_chandrupatla` (but containing the current + iterate's values of all variables). If `callback` raises a + ``StopIteration``, the algorithm will terminate immediately and + `_chandrupatla` will return a result. + + Returns + ------- + res : _RichResult + An instance of `scipy._lib._util._RichResult` with the following + attributes. The descriptions are written as though the values will be + scalars; however, if `func` returns an array, the outputs will be + arrays of the same shape. + + x : float + The root of the function, if the algorithm terminated successfully. + nfev : int + The number of times the function was called to find the root. + nit : int + The number of iterations of Chandrupatla's algorithm performed. + status : int + An integer representing the exit status of the algorithm. + ``0`` : The algorithm converged to the specified tolerances. + ``-1`` : The algorithm encountered an invalid bracket. + ``-2`` : The maximum number of iterations was reached. + ``-3`` : A non-finite value was encountered. + ``-4`` : Iteration was terminated by `callback`. + ``1`` : The algorithm is proceeding normally (in `callback` only). + success : bool + ``True`` when the algorithm terminated successfully (status ``0``). + fun : float + The value of `func` evaluated at `x`. + xl, xr : float + The lower and upper ends of the bracket. + fl, fr : float + The function value at the lower and upper ends of the bracket. + + Notes + ----- + Implemented based on Chandrupatla's original paper [1]_. + + If ``xl`` and ``xr`` are the left and right ends of the bracket, + ``xmin = xl if abs(func(xl)) <= abs(func(xr)) else xr``, + and ``fmin0 = min(func(a), func(b))``, then the algorithm is considered to + have converged when ``abs(xr - xl) < xatol + abs(xmin) * xrtol`` or + ``fun(xmin) <= fatol + abs(fmin0) * frtol``. This is equivalent to the + termination condition described in [1]_ with ``xrtol = 4e-10``, + ``xatol = 1e-5``, and ``fatol = frtol = 0``. The default values are + ``xatol = 4*tiny``, ``xrtol = 4*eps``, ``frtol = 0``, and ``fatol = tiny``, + where ``eps`` and ``tiny`` are the precision and smallest normal number + of the result ``dtype`` of function inputs and outputs. + + References + ---------- + + .. [1] Chandrupatla, Tirupathi R. + "A new hybrid quadratic/bisection algorithm for finding the zero of a + nonlinear function without using derivatives". + Advances in Engineering Software, 28(3), 145-149. + https://doi.org/10.1016/s0965-9978(96)00051-8 + + See Also + -------- + brentq, brenth, ridder, bisect, newton + + Examples + -------- + >>> from scipy import optimize + >>> def f(x, c): + ... return x**3 - 2*x - c + >>> c = 5 + >>> res = optimize._chandrupatla._chandrupatla(f, 0, 3, args=(c,)) + >>> res.x + 2.0945514818937463 + + >>> c = [3, 4, 5] + >>> res = optimize._chandrupatla._chandrupatla(f, 0, 3, args=(c,)) + >>> res.x + array([1.8932892 , 2. , 2.09455148]) + + """ + res = _chandrupatla_iv(func, args, xatol, xrtol, + fatol, frtol, maxiter, callback) + func, args, xatol, xrtol, fatol, frtol, maxiter, callback = res + + # Initialization + temp = eim._initialize(func, (a, b), args) + func, xs, fs, args, shape, dtype, xp = temp + x1, x2 = xs + f1, f2 = fs + status = xp.full_like(x1, eim._EINPROGRESS, dtype=xp.int32) # in progress + nit, nfev = 0, 2 # two function evaluations performed above + finfo = xp.finfo(dtype) + xatol = 4*finfo.smallest_normal if xatol is None else xatol + xrtol = 4*finfo.eps if xrtol is None else xrtol + fatol = finfo.smallest_normal if fatol is None else fatol + frtol = frtol * xp_minimum(xp.abs(f1), xp.abs(f2)) + maxiter = (math.log2(finfo.max) - math.log2(finfo.smallest_normal) + if maxiter is None else maxiter) + work = _RichResult(x1=x1, f1=f1, x2=x2, f2=f2, x3=None, f3=None, t=0.5, + xatol=xatol, xrtol=xrtol, fatol=fatol, frtol=frtol, + nit=nit, nfev=nfev, status=status) + res_work_pairs = [('status', 'status'), ('x', 'xmin'), ('fun', 'fmin'), + ('nit', 'nit'), ('nfev', 'nfev'), ('xl', 'x1'), + ('fl', 'f1'), ('xr', 'x2'), ('fr', 'f2')] + + def pre_func_eval(work): + # [1] Figure 1 (first box) + x = work.x1 + work.t * (work.x2 - work.x1) + return x + + def post_func_eval(x, f, work): + # [1] Figure 1 (first diamond and boxes) + # Note: y/n are reversed in figure; compare to BASIC in appendix + work.x3, work.f3 = (xp.asarray(work.x2, copy=True), + xp.asarray(work.f2, copy=True)) + j = xp.sign(f) == xp.sign(work.f1) + nj = ~j + work.x3[j], work.f3[j] = work.x1[j], work.f1[j] + work.x2[nj], work.f2[nj] = work.x1[nj], work.f1[nj] + work.x1, work.f1 = x, f + + def check_termination(work): + # [1] Figure 1 (second diamond) + # Check for all terminal conditions and record statuses. + + # See [1] Section 4 (first two sentences) + i = xp.abs(work.f1) < xp.abs(work.f2) + work.xmin = xp.where(i, work.x1, work.x2) + work.fmin = xp.where(i, work.f1, work.f2) + stop = xp.zeros_like(work.x1, dtype=xp.bool) # termination condition met + + # If function value tolerance is met, report successful convergence, + # regardless of other conditions. Note that `frtol` has been redefined + # as `frtol = frtol * minimum(f1, f2)`, where `f1` and `f2` are the + # function evaluated at the original ends of the bracket. + i = xp.abs(work.fmin) <= work.fatol + work.frtol + work.status[i] = eim._ECONVERGED + stop[i] = True + + # If the bracket is no longer valid, report failure (unless a function + # tolerance is met, as detected above). + i = (xp_sign(work.f1) == xp_sign(work.f2)) & ~stop + NaN = xp.asarray(xp.nan, dtype=work.xmin.dtype) + work.xmin[i], work.fmin[i], work.status[i] = NaN, NaN, eim._ESIGNERR + stop[i] = True + + # If the abscissae are non-finite or either function value is NaN, + # report failure. + x_nonfinite = ~(xp.isfinite(work.x1) & xp.isfinite(work.x2)) + f_nan = xp.isnan(work.f1) & xp.isnan(work.f2) + i = (x_nonfinite | f_nan) & ~stop + work.xmin[i], work.fmin[i], work.status[i] = NaN, NaN, eim._EVALUEERR + stop[i] = True + + # This is the convergence criterion used in bisect. Chandrupatla's + # criterion is equivalent to this except with a factor of 4 on `xrtol`. + work.dx = xp.abs(work.x2 - work.x1) + work.tol = xp.abs(work.xmin) * work.xrtol + work.xatol + i = work.dx < work.tol + work.status[i] = eim._ECONVERGED + stop[i] = True + + return stop + + def post_termination_check(work): + # [1] Figure 1 (third diamond and boxes / Equation 1) + xi1 = (work.x1 - work.x2) / (work.x3 - work.x2) + phi1 = (work.f1 - work.f2) / (work.f3 - work.f2) + alpha = (work.x3 - work.x1) / (work.x2 - work.x1) + j = ((1 - xp.sqrt(1 - xi1)) < phi1) & (phi1 < xp.sqrt(xi1)) + + f1j, f2j, f3j, alphaj = work.f1[j], work.f2[j], work.f3[j], alpha[j] + t = xp.full_like(alpha, 0.5) + t[j] = (f1j / (f1j - f2j) * f3j / (f3j - f2j) + - alphaj * f1j / (f3j - f1j) * f2j / (f2j - f3j)) + + # [1] Figure 1 (last box; see also BASIC in appendix with comment + # "Adjust T Away from the Interval Boundary") + tl = 0.5 * work.tol / work.dx + work.t = xp_clip(t, tl, 1 - tl) + + def customize_result(res, shape): + xl, xr, fl, fr = res['xl'], res['xr'], res['fl'], res['fr'] + i = res['xl'] < res['xr'] + res['xl'] = xp.where(i, xl, xr) + res['xr'] = xp.where(i, xr, xl) + res['fl'] = xp.where(i, fl, fr) + res['fr'] = xp.where(i, fr, fl) + return shape + + return eim._loop(work, callback, shape, maxiter, func, args, dtype, + pre_func_eval, post_func_eval, check_termination, + post_termination_check, customize_result, res_work_pairs, + xp=xp) + + +def _chandrupatla_iv(func, args, xatol, xrtol, + fatol, frtol, maxiter, callback): + # Input validation for `_chandrupatla` + + if not callable(func): + raise ValueError('`func` must be callable.') + + if not np.iterable(args): + args = (args,) + + # tolerances are floats, not arrays; OK to use NumPy + tols = np.asarray([xatol if xatol is not None else 1, + xrtol if xrtol is not None else 1, + fatol if fatol is not None else 1, + frtol if frtol is not None else 1]) + if (not np.issubdtype(tols.dtype, np.number) or np.any(tols < 0) + or np.any(np.isnan(tols)) or tols.shape != (4,)): + raise ValueError('Tolerances must be non-negative scalars.') + + if maxiter is not None: + maxiter_int = int(maxiter) + if maxiter != maxiter_int or maxiter < 0: + raise ValueError('`maxiter` must be a non-negative integer.') + + if callback is not None and not callable(callback): + raise ValueError('`callback` must be callable.') + + return func, args, xatol, xrtol, fatol, frtol, maxiter, callback + + +def _chandrupatla_minimize(func, x1, x2, x3, *, args=(), xatol=None, + xrtol=None, fatol=None, frtol=None, maxiter=100, + callback=None): + """Find the minimizer of an elementwise function. + + For each element of the output of `func`, `_chandrupatla_minimize` seeks + the scalar minimizer that minimizes the element. This function allows for + `x1`, `x2`, `x3`, and the elements of `args` to be arrays of any + broadcastable shapes. + + Parameters + ---------- + func : callable + The function whose minimizer is desired. The signature must be:: + + func(x: ndarray, *args) -> ndarray + + where each element of ``x`` is a finite real and ``args`` is a tuple, + which may contain an arbitrary number of arrays that are broadcastable + with `x`. ``func`` must be an elementwise function: each element + ``func(x)[i]`` must equal ``func(x[i])`` for all indices ``i``. + `_chandrupatla` seeks an array ``x`` such that ``func(x)`` is an array + of minima. + x1, x2, x3 : array_like + The abscissae of a standard scalar minimization bracket. A bracket is + valid if ``x1 < x2 < x3`` and ``func(x1) > func(x2) <= func(x3)``. + Must be broadcastable with one another and `args`. + args : tuple, optional + Additional positional arguments to be passed to `func`. Must be arrays + broadcastable with `x1`, `x2`, and `x3`. If the callable to be + differentiated requires arguments that are not broadcastable with `x`, + wrap that callable with `func` such that `func` accepts only `x` and + broadcastable arrays. + xatol, xrtol, fatol, frtol : float, optional + Absolute and relative tolerances on the minimizer and function value. + See Notes for details. + maxiter : int, optional + The maximum number of iterations of the algorithm to perform. + callback : callable, optional + An optional user-supplied function to be called before the first + iteration and after each iteration. + Called as ``callback(res)``, where ``res`` is a ``_RichResult`` + similar to that returned by `_chandrupatla_minimize` (but containing + the current iterate's values of all variables). If `callback` raises a + ``StopIteration``, the algorithm will terminate immediately and + `_chandrupatla_minimize` will return a result. + + Returns + ------- + res : _RichResult + An instance of `scipy._lib._util._RichResult` with the following + attributes. (The descriptions are written as though the values will be + scalars; however, if `func` returns an array, the outputs will be + arrays of the same shape.) + + success : bool + ``True`` when the algorithm terminated successfully (status ``0``). + status : int + An integer representing the exit status of the algorithm. + ``0`` : The algorithm converged to the specified tolerances. + ``-1`` : The algorithm encountered an invalid bracket. + ``-2`` : The maximum number of iterations was reached. + ``-3`` : A non-finite value was encountered. + ``-4`` : Iteration was terminated by `callback`. + ``1`` : The algorithm is proceeding normally (in `callback` only). + x : float + The minimizer of the function, if the algorithm terminated + successfully. + fun : float + The value of `func` evaluated at `x`. + nfev : int + The number of points at which `func` was evaluated. + nit : int + The number of iterations of the algorithm that were performed. + xl, xm, xr : float + The final three-point bracket. + fl, fm, fr : float + The function value at the bracket points. + + Notes + ----- + Implemented based on Chandrupatla's original paper [1]_. + + If ``x1 < x2 < x3`` are the points of the bracket and ``f1 > f2 <= f3`` + are the values of ``func`` at those points, then the algorithm is + considered to have converged when ``x3 - x1 <= abs(x2)*xrtol + xatol`` + or ``(f1 - 2*f2 + f3)/2 <= abs(f2)*frtol + fatol``. Note that first of + these differs from the termination conditions described in [1]_. The + default values of `xrtol` is the square root of the precision of the + appropriate dtype, and ``xatol = fatol = frtol`` is the smallest normal + number of the appropriate dtype. + + References + ---------- + .. [1] Chandrupatla, Tirupathi R. (1998). + "An efficient quadratic fit-sectioning algorithm for minimization + without derivatives". + Computer Methods in Applied Mechanics and Engineering, 152 (1-2), + 211-217. https://doi.org/10.1016/S0045-7825(97)00190-4 + + See Also + -------- + golden, brent, bounded + + Examples + -------- + >>> from scipy.optimize._chandrupatla import _chandrupatla_minimize + >>> def f(x, args=1): + ... return (x - args)**2 + >>> res = _chandrupatla_minimize(f, -5, 0, 5) + >>> res.x + 1.0 + >>> c = [1, 1.5, 2] + >>> res = _chandrupatla_minimize(f, -5, 0, 5, args=(c,)) + >>> res.x + array([1. , 1.5, 2. ]) + """ + res = _chandrupatla_iv(func, args, xatol, xrtol, + fatol, frtol, maxiter, callback) + func, args, xatol, xrtol, fatol, frtol, maxiter, callback = res + + # Initialization + xs = (x1, x2, x3) + temp = eim._initialize(func, xs, args) + func, xs, fs, args, shape, dtype, xp = temp # line split for PEP8 + x1, x2, x3 = xs + f1, f2, f3 = fs + phi = dtype.type(0.5 + 0.5*5**0.5) # golden ratio + status = np.full_like(x1, eim._EINPROGRESS, dtype=int) # in progress + nit, nfev = 0, 3 # three function evaluations performed above + fatol = np.finfo(dtype).tiny if fatol is None else fatol + frtol = np.finfo(dtype).tiny if frtol is None else frtol + xatol = np.finfo(dtype).tiny if xatol is None else xatol + xrtol = np.sqrt(np.finfo(dtype).eps) if xrtol is None else xrtol + + # Ensure that x1 < x2 < x3 initially. + xs, fs = np.vstack((x1, x2, x3)), np.vstack((f1, f2, f3)) + i = np.argsort(xs, axis=0) + x1, x2, x3 = np.take_along_axis(xs, i, axis=0) + f1, f2, f3 = np.take_along_axis(fs, i, axis=0) + q0 = x3.copy() # "At the start, q0 is set at x3..." ([1] after (7)) + + work = _RichResult(x1=x1, f1=f1, x2=x2, f2=f2, x3=x3, f3=f3, phi=phi, + xatol=xatol, xrtol=xrtol, fatol=fatol, frtol=frtol, + nit=nit, nfev=nfev, status=status, q0=q0, args=args) + res_work_pairs = [('status', 'status'), + ('x', 'x2'), ('fun', 'f2'), + ('nit', 'nit'), ('nfev', 'nfev'), + ('xl', 'x1'), ('xm', 'x2'), ('xr', 'x3'), + ('fl', 'f1'), ('fm', 'f2'), ('fr', 'f3')] + + def pre_func_eval(work): + # `_check_termination` is called first -> `x3 - x2 > x2 - x1` + # But let's calculate a few terms that we'll reuse + x21 = work.x2 - work.x1 + x32 = work.x3 - work.x2 + + # [1] Section 3. "The quadratic minimum point Q1 is calculated using + # the relations developed in the previous section." [1] Section 2 (5/6) + A = x21 * (work.f3 - work.f2) + B = x32 * (work.f1 - work.f2) + C = A / (A + B) + # q1 = C * (work.x1 + work.x2) / 2 + (1 - C) * (work.x2 + work.x3) / 2 + q1 = 0.5 * (C*(work.x1 - work.x3) + work.x2 + work.x3) # much faster + # this is an array, so multiplying by 0.5 does not change dtype + + # "If Q1 and Q0 are sufficiently close... Q1 is accepted if it is + # sufficiently away from the inside point x2" + i = abs(q1 - work.q0) < 0.5 * abs(x21) # [1] (7) + xi = q1[i] + # Later, after (9), "If the point Q1 is in a +/- xtol neighborhood of + # x2, the new point is chosen in the larger interval at a distance + # tol away from x2." + # See also QBASIC code after "Accept Ql adjust if close to X2". + j = abs(q1[i] - work.x2[i]) <= work.xtol[i] + xi[j] = work.x2[i][j] + np.sign(x32[i][j]) * work.xtol[i][j] + + # "If condition (7) is not satisfied, golden sectioning of the larger + # interval is carried out to introduce the new point." + # (For simplicity, we go ahead and calculate it for all points, but we + # change the elements for which the condition was satisfied.) + x = work.x2 + (2 - work.phi) * x32 + x[i] = xi + + # "We define Q0 as the value of Q1 at the previous iteration." + work.q0 = q1 + return x + + def post_func_eval(x, f, work): + # Standard logic for updating a three-point bracket based on a new + # point. In QBASIC code, see "IF SGN(X-X2) = SGN(X3-X2) THEN...". + # There is an awful lot of data copying going on here; this would + # probably benefit from code optimization or implementation in Pythran. + i = np.sign(x - work.x2) == np.sign(work.x3 - work.x2) + xi, x1i, x2i, x3i = x[i], work.x1[i], work.x2[i], work.x3[i], + fi, f1i, f2i, f3i = f[i], work.f1[i], work.f2[i], work.f3[i] + j = fi > f2i + x3i[j], f3i[j] = xi[j], fi[j] + j = ~j + x1i[j], f1i[j], x2i[j], f2i[j] = x2i[j], f2i[j], xi[j], fi[j] + + ni = ~i + xni, x1ni, x2ni, x3ni = x[ni], work.x1[ni], work.x2[ni], work.x3[ni], + fni, f1ni, f2ni, f3ni = f[ni], work.f1[ni], work.f2[ni], work.f3[ni] + j = fni > f2ni + x1ni[j], f1ni[j] = xni[j], fni[j] + j = ~j + x3ni[j], f3ni[j], x2ni[j], f2ni[j] = x2ni[j], f2ni[j], xni[j], fni[j] + + work.x1[i], work.x2[i], work.x3[i] = x1i, x2i, x3i + work.f1[i], work.f2[i], work.f3[i] = f1i, f2i, f3i + work.x1[ni], work.x2[ni], work.x3[ni] = x1ni, x2ni, x3ni, + work.f1[ni], work.f2[ni], work.f3[ni] = f1ni, f2ni, f3ni + + def check_termination(work): + # Check for all terminal conditions and record statuses. + stop = np.zeros_like(work.x1, dtype=bool) # termination condition met + + # Bracket is invalid; stop and don't return minimizer/minimum + i = ((work.f2 > work.f1) | (work.f2 > work.f3)) + work.x2[i], work.f2[i] = np.nan, np.nan + stop[i], work.status[i] = True, eim._ESIGNERR + + # Non-finite values; stop and don't return minimizer/minimum + finite = np.isfinite(work.x1+work.x2+work.x3+work.f1+work.f2+work.f3) + i = ~(finite | stop) + work.x2[i], work.f2[i] = np.nan, np.nan + stop[i], work.status[i] = True, eim._EVALUEERR + + # [1] Section 3 "Points 1 and 3 are interchanged if necessary to make + # the (x2, x3) the larger interval." + # Note: I had used np.choose; this is much faster. This would be a good + # place to save e.g. `work.x3 - work.x2` for reuse, but I tried and + # didn't notice a speed boost, so let's keep it simple. + i = abs(work.x3 - work.x2) < abs(work.x2 - work.x1) + temp = work.x1[i] + work.x1[i] = work.x3[i] + work.x3[i] = temp + temp = work.f1[i] + work.f1[i] = work.f3[i] + work.f3[i] = temp + + # [1] Section 3 (bottom of page 212) + # "We set a tolerance value xtol..." + work.xtol = abs(work.x2) * work.xrtol + work.xatol # [1] (8) + # "The convergence based on interval is achieved when..." + # Note: Equality allowed in case of `xtol=0` + i = abs(work.x3 - work.x2) <= 2 * work.xtol # [1] (9) + + # "We define ftol using..." + ftol = abs(work.f2) * work.frtol + work.fatol # [1] (10) + # "The convergence based on function values is achieved when..." + # Note 1: modify in place to incorporate tolerance on function value. + # Note 2: factor of 2 is not in the text; see QBASIC start of DO loop + i |= (work.f1 - 2 * work.f2 + work.f3) <= 2*ftol # [1] (11) + i &= ~stop + stop[i], work.status[i] = True, eim._ECONVERGED + + return stop + + def post_termination_check(work): + pass + + def customize_result(res, shape): + xl, xr, fl, fr = res['xl'], res['xr'], res['fl'], res['fr'] + i = res['xl'] < res['xr'] + res['xl'] = np.choose(i, (xr, xl)) + res['xr'] = np.choose(i, (xl, xr)) + res['fl'] = np.choose(i, (fr, fl)) + res['fr'] = np.choose(i, (fl, fr)) + return shape + + return eim._loop(work, callback, shape, maxiter, func, args, dtype, + pre_func_eval, post_func_eval, check_termination, + post_termination_check, customize_result, res_work_pairs, + xp=xp) diff --git a/llava_next/lib/python3.10/site-packages/scipy/optimize/_cobyla_py.py b/llava_next/lib/python3.10/site-packages/scipy/optimize/_cobyla_py.py new file mode 100644 index 0000000000000000000000000000000000000000..9007fe38a06a91fe456e64d74f4c0e37800f0607 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/scipy/optimize/_cobyla_py.py @@ -0,0 +1,316 @@ +""" +Interface to Constrained Optimization By Linear Approximation + +Functions +--------- +.. autosummary:: + :toctree: generated/ + + fmin_cobyla + +""" + +import functools +from threading import RLock + +import numpy as np +from scipy.optimize import _cobyla as cobyla +from ._optimize import (OptimizeResult, _check_unknown_options, + _prepare_scalar_function) +try: + from itertools import izip +except ImportError: + izip = zip + +__all__ = ['fmin_cobyla'] + +# Workaround as _cobyla.minimize is not threadsafe +# due to an unknown f2py bug and can segfault, +# see gh-9658. +_module_lock = RLock() +def synchronized(func): + @functools.wraps(func) + def wrapper(*args, **kwargs): + with _module_lock: + return func(*args, **kwargs) + return wrapper + +@synchronized +def fmin_cobyla(func, x0, cons, args=(), consargs=None, rhobeg=1.0, + rhoend=1e-4, maxfun=1000, disp=None, catol=2e-4, + *, callback=None): + """ + Minimize a function using the Constrained Optimization By Linear + Approximation (COBYLA) method. This method wraps a FORTRAN + implementation of the algorithm. + + Parameters + ---------- + func : callable + Function to minimize. In the form func(x, \\*args). + x0 : ndarray + Initial guess. + cons : sequence + Constraint functions; must all be ``>=0`` (a single function + if only 1 constraint). Each function takes the parameters `x` + as its first argument, and it can return either a single number or + an array or list of numbers. + args : tuple, optional + Extra arguments to pass to function. + consargs : tuple, optional + Extra arguments to pass to constraint functions (default of None means + use same extra arguments as those passed to func). + Use ``()`` for no extra arguments. + rhobeg : float, optional + Reasonable initial changes to the variables. + rhoend : float, optional + Final accuracy in the optimization (not precisely guaranteed). This + is a lower bound on the size of the trust region. + disp : {0, 1, 2, 3}, optional + Controls the frequency of output; 0 implies no output. + maxfun : int, optional + Maximum number of function evaluations. + catol : float, optional + Absolute tolerance for constraint violations. + callback : callable, optional + Called after each iteration, as ``callback(x)``, where ``x`` is the + current parameter vector. + + Returns + ------- + x : ndarray + The argument that minimises `f`. + + See also + -------- + minimize: Interface to minimization algorithms for multivariate + functions. See the 'COBYLA' `method` in particular. + + Notes + ----- + This algorithm is based on linear approximations to the objective + function and each constraint. We briefly describe the algorithm. + + Suppose the function is being minimized over k variables. At the + jth iteration the algorithm has k+1 points v_1, ..., v_(k+1), + an approximate solution x_j, and a radius RHO_j. + (i.e., linear plus a constant) approximations to the objective + function and constraint functions such that their function values + agree with the linear approximation on the k+1 points v_1,.., v_(k+1). + This gives a linear program to solve (where the linear approximations + of the constraint functions are constrained to be non-negative). + + However, the linear approximations are likely only good + approximations near the current simplex, so the linear program is + given the further requirement that the solution, which + will become x_(j+1), must be within RHO_j from x_j. RHO_j only + decreases, never increases. The initial RHO_j is rhobeg and the + final RHO_j is rhoend. In this way COBYLA's iterations behave + like a trust region algorithm. + + Additionally, the linear program may be inconsistent, or the + approximation may give poor improvement. For details about + how these issues are resolved, as well as how the points v_i are + updated, refer to the source code or the references below. + + + References + ---------- + Powell M.J.D. (1994), "A direct search optimization method that models + the objective and constraint functions by linear interpolation.", in + Advances in Optimization and Numerical Analysis, eds. S. Gomez and + J-P Hennart, Kluwer Academic (Dordrecht), pp. 51-67 + + Powell M.J.D. (1998), "Direct search algorithms for optimization + calculations", Acta Numerica 7, 287-336 + + Powell M.J.D. (2007), "A view of algorithms for optimization without + derivatives", Cambridge University Technical Report DAMTP 2007/NA03 + + + Examples + -------- + Minimize the objective function f(x,y) = x*y subject + to the constraints x**2 + y**2 < 1 and y > 0:: + + >>> def objective(x): + ... return x[0]*x[1] + ... + >>> def constr1(x): + ... return 1 - (x[0]**2 + x[1]**2) + ... + >>> def constr2(x): + ... return x[1] + ... + >>> from scipy.optimize import fmin_cobyla + >>> fmin_cobyla(objective, [0.0, 0.1], [constr1, constr2], rhoend=1e-7) + array([-0.70710685, 0.70710671]) + + The exact solution is (-sqrt(2)/2, sqrt(2)/2). + + + + """ + err = "cons must be a sequence of callable functions or a single"\ + " callable function." + try: + len(cons) + except TypeError as e: + if callable(cons): + cons = [cons] + else: + raise TypeError(err) from e + else: + for thisfunc in cons: + if not callable(thisfunc): + raise TypeError(err) + + if consargs is None: + consargs = args + + # build constraints + con = tuple({'type': 'ineq', 'fun': c, 'args': consargs} for c in cons) + + # options + opts = {'rhobeg': rhobeg, + 'tol': rhoend, + 'disp': disp, + 'maxiter': maxfun, + 'catol': catol, + 'callback': callback} + + sol = _minimize_cobyla(func, x0, args, constraints=con, + **opts) + if disp and not sol['success']: + print(f"COBYLA failed to find a solution: {sol.message}") + return sol['x'] + + +@synchronized +def _minimize_cobyla(fun, x0, args=(), constraints=(), + rhobeg=1.0, tol=1e-4, maxiter=1000, + disp=False, catol=2e-4, callback=None, bounds=None, + **unknown_options): + """ + Minimize a scalar function of one or more variables using the + Constrained Optimization BY Linear Approximation (COBYLA) algorithm. + + Options + ------- + rhobeg : float + Reasonable initial changes to the variables. + tol : float + Final accuracy in the optimization (not precisely guaranteed). + This is a lower bound on the size of the trust region. + disp : bool + Set to True to print convergence messages. If False, + `verbosity` is ignored as set to 0. + maxiter : int + Maximum number of function evaluations. + catol : float + Tolerance (absolute) for constraint violations + + """ + _check_unknown_options(unknown_options) + maxfun = maxiter + rhoend = tol + iprint = int(bool(disp)) + + # check constraints + if isinstance(constraints, dict): + constraints = (constraints, ) + + if bounds: + i_lb = np.isfinite(bounds.lb) + if np.any(i_lb): + def lb_constraint(x, *args, **kwargs): + return x[i_lb] - bounds.lb[i_lb] + + constraints.append({'type': 'ineq', 'fun': lb_constraint}) + + i_ub = np.isfinite(bounds.ub) + if np.any(i_ub): + def ub_constraint(x): + return bounds.ub[i_ub] - x[i_ub] + + constraints.append({'type': 'ineq', 'fun': ub_constraint}) + + for ic, con in enumerate(constraints): + # check type + try: + ctype = con['type'].lower() + except KeyError as e: + raise KeyError('Constraint %d has no type defined.' % ic) from e + except TypeError as e: + raise TypeError('Constraints must be defined using a ' + 'dictionary.') from e + except AttributeError as e: + raise TypeError("Constraint's type must be a string.") from e + else: + if ctype != 'ineq': + raise ValueError("Constraints of type '%s' not handled by " + "COBYLA." % con['type']) + + # check function + if 'fun' not in con: + raise KeyError('Constraint %d has no function defined.' % ic) + + # check extra arguments + if 'args' not in con: + con['args'] = () + + # m is the total number of constraint values + # it takes into account that some constraints may be vector-valued + cons_lengths = [] + for c in constraints: + f = c['fun'](x0, *c['args']) + try: + cons_length = len(f) + except TypeError: + cons_length = 1 + cons_lengths.append(cons_length) + m = sum(cons_lengths) + + # create the ScalarFunction, cobyla doesn't require derivative function + def _jac(x, *args): + return None + + sf = _prepare_scalar_function(fun, x0, args=args, jac=_jac) + + def calcfc(x, con): + f = sf.fun(x) + i = 0 + for size, c in izip(cons_lengths, constraints): + con[i: i + size] = c['fun'](x, *c['args']) + i += size + return f + + def wrapped_callback(x): + if callback is not None: + callback(np.copy(x)) + + info = np.zeros(4, np.float64) + xopt, info = cobyla.minimize(calcfc, m=m, x=np.copy(x0), rhobeg=rhobeg, + rhoend=rhoend, iprint=iprint, maxfun=maxfun, + dinfo=info, callback=wrapped_callback) + + if info[3] > catol: + # Check constraint violation + info[0] = 4 + + return OptimizeResult(x=xopt, + status=int(info[0]), + success=info[0] == 1, + message={1: 'Optimization terminated successfully.', + 2: 'Maximum number of function evaluations ' + 'has been exceeded.', + 3: 'Rounding errors are becoming damaging ' + 'in COBYLA subroutine.', + 4: 'Did not converge to a solution ' + 'satisfying the constraints. See ' + '`maxcv` for magnitude of violation.', + 5: 'NaN result encountered.' + }.get(info[0], 'Unknown exit status.'), + nfev=int(info[1]), + fun=info[2], + maxcv=info[3]) diff --git a/llava_next/lib/python3.10/site-packages/scipy/optimize/_constraints.py b/llava_next/lib/python3.10/site-packages/scipy/optimize/_constraints.py new file mode 100644 index 0000000000000000000000000000000000000000..1c7ff5e170b2eb518bc6be0c667ac9f89a073dcf --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/scipy/optimize/_constraints.py @@ -0,0 +1,590 @@ +"""Constraints definition for minimize.""" +import numpy as np +from ._hessian_update_strategy import BFGS +from ._differentiable_functions import ( + VectorFunction, LinearVectorFunction, IdentityVectorFunction) +from ._optimize import OptimizeWarning +from warnings import warn, catch_warnings, simplefilter, filterwarnings +from scipy.sparse import issparse + + +def _arr_to_scalar(x): + # If x is a numpy array, return x.item(). This will + # fail if the array has more than one element. + return x.item() if isinstance(x, np.ndarray) else x + + +class NonlinearConstraint: + """Nonlinear constraint on the variables. + + The constraint has the general inequality form:: + + lb <= fun(x) <= ub + + Here the vector of independent variables x is passed as ndarray of shape + (n,) and ``fun`` returns a vector with m components. + + It is possible to use equal bounds to represent an equality constraint or + infinite bounds to represent a one-sided constraint. + + Parameters + ---------- + fun : callable + The function defining the constraint. + The signature is ``fun(x) -> array_like, shape (m,)``. + lb, ub : array_like + Lower and upper bounds on the constraint. Each array must have the + shape (m,) or be a scalar, in the latter case a bound will be the same + for all components of the constraint. Use ``np.inf`` with an + appropriate sign to specify a one-sided constraint. + Set components of `lb` and `ub` equal to represent an equality + constraint. Note that you can mix constraints of different types: + interval, one-sided or equality, by setting different components of + `lb` and `ub` as necessary. + jac : {callable, '2-point', '3-point', 'cs'}, optional + Method of computing the Jacobian matrix (an m-by-n matrix, + where element (i, j) is the partial derivative of f[i] with + respect to x[j]). The keywords {'2-point', '3-point', + 'cs'} select a finite difference scheme for the numerical estimation. + A callable must have the following signature: + ``jac(x) -> {ndarray, sparse matrix}, shape (m, n)``. + Default is '2-point'. + hess : {callable, '2-point', '3-point', 'cs', HessianUpdateStrategy, None}, optional + Method for computing the Hessian matrix. The keywords + {'2-point', '3-point', 'cs'} select a finite difference scheme for + numerical estimation. Alternatively, objects implementing + `HessianUpdateStrategy` interface can be used to approximate the + Hessian. Currently available implementations are: + + - `BFGS` (default option) + - `SR1` + + A callable must return the Hessian matrix of ``dot(fun, v)`` and + must have the following signature: + ``hess(x, v) -> {LinearOperator, sparse matrix, array_like}, shape (n, n)``. + Here ``v`` is ndarray with shape (m,) containing Lagrange multipliers. + keep_feasible : array_like of bool, optional + Whether to keep the constraint components feasible throughout + iterations. A single value set this property for all components. + Default is False. Has no effect for equality constraints. + finite_diff_rel_step: None or array_like, optional + Relative step size for the finite difference approximation. Default is + None, which will select a reasonable value automatically depending + on a finite difference scheme. + finite_diff_jac_sparsity: {None, array_like, sparse matrix}, optional + Defines the sparsity structure of the Jacobian matrix for finite + difference estimation, its shape must be (m, n). If the Jacobian has + only few non-zero elements in *each* row, providing the sparsity + structure will greatly speed up the computations. A zero entry means + that a corresponding element in the Jacobian is identically zero. + If provided, forces the use of 'lsmr' trust-region solver. + If None (default) then dense differencing will be used. + + Notes + ----- + Finite difference schemes {'2-point', '3-point', 'cs'} may be used for + approximating either the Jacobian or the Hessian. We, however, do not allow + its use for approximating both simultaneously. Hence whenever the Jacobian + is estimated via finite-differences, we require the Hessian to be estimated + using one of the quasi-Newton strategies. + + The scheme 'cs' is potentially the most accurate, but requires the function + to correctly handles complex inputs and be analytically continuable to the + complex plane. The scheme '3-point' is more accurate than '2-point' but + requires twice as many operations. + + Examples + -------- + Constrain ``x[0] < sin(x[1]) + 1.9`` + + >>> from scipy.optimize import NonlinearConstraint + >>> import numpy as np + >>> con = lambda x: x[0] - np.sin(x[1]) + >>> nlc = NonlinearConstraint(con, -np.inf, 1.9) + + """ + def __init__(self, fun, lb, ub, jac='2-point', hess=BFGS(), + keep_feasible=False, finite_diff_rel_step=None, + finite_diff_jac_sparsity=None): + self.fun = fun + self.lb = lb + self.ub = ub + self.finite_diff_rel_step = finite_diff_rel_step + self.finite_diff_jac_sparsity = finite_diff_jac_sparsity + self.jac = jac + self.hess = hess + self.keep_feasible = keep_feasible + + +class LinearConstraint: + """Linear constraint on the variables. + + The constraint has the general inequality form:: + + lb <= A.dot(x) <= ub + + Here the vector of independent variables x is passed as ndarray of shape + (n,) and the matrix A has shape (m, n). + + It is possible to use equal bounds to represent an equality constraint or + infinite bounds to represent a one-sided constraint. + + Parameters + ---------- + A : {array_like, sparse matrix}, shape (m, n) + Matrix defining the constraint. + lb, ub : dense array_like, optional + Lower and upper limits on the constraint. Each array must have the + shape (m,) or be a scalar, in the latter case a bound will be the same + for all components of the constraint. Use ``np.inf`` with an + appropriate sign to specify a one-sided constraint. + Set components of `lb` and `ub` equal to represent an equality + constraint. Note that you can mix constraints of different types: + interval, one-sided or equality, by setting different components of + `lb` and `ub` as necessary. Defaults to ``lb = -np.inf`` + and ``ub = np.inf`` (no limits). + keep_feasible : dense array_like of bool, optional + Whether to keep the constraint components feasible throughout + iterations. A single value set this property for all components. + Default is False. Has no effect for equality constraints. + """ + def _input_validation(self): + if self.A.ndim != 2: + message = "`A` must have exactly two dimensions." + raise ValueError(message) + + try: + shape = self.A.shape[0:1] + self.lb = np.broadcast_to(self.lb, shape) + self.ub = np.broadcast_to(self.ub, shape) + self.keep_feasible = np.broadcast_to(self.keep_feasible, shape) + except ValueError: + message = ("`lb`, `ub`, and `keep_feasible` must be broadcastable " + "to shape `A.shape[0:1]`") + raise ValueError(message) + + def __init__(self, A, lb=-np.inf, ub=np.inf, keep_feasible=False): + if not issparse(A): + # In some cases, if the constraint is not valid, this emits a + # VisibleDeprecationWarning about ragged nested sequences + # before eventually causing an error. `scipy.optimize.milp` would + # prefer that this just error out immediately so it can handle it + # rather than concerning the user. + with catch_warnings(): + simplefilter("error") + self.A = np.atleast_2d(A).astype(np.float64) + else: + self.A = A + if issparse(lb) or issparse(ub): + raise ValueError("Constraint limits must be dense arrays.") + self.lb = np.atleast_1d(lb).astype(np.float64) + self.ub = np.atleast_1d(ub).astype(np.float64) + + if issparse(keep_feasible): + raise ValueError("`keep_feasible` must be a dense array.") + self.keep_feasible = np.atleast_1d(keep_feasible).astype(bool) + self._input_validation() + + def residual(self, x): + """ + Calculate the residual between the constraint function and the limits + + For a linear constraint of the form:: + + lb <= A@x <= ub + + the lower and upper residuals between ``A@x`` and the limits are values + ``sl`` and ``sb`` such that:: + + lb + sl == A@x == ub - sb + + When all elements of ``sl`` and ``sb`` are positive, all elements of + the constraint are satisfied; a negative element in ``sl`` or ``sb`` + indicates that the corresponding element of the constraint is not + satisfied. + + Parameters + ---------- + x: array_like + Vector of independent variables + + Returns + ------- + sl, sb : array-like + The lower and upper residuals + """ + return self.A@x - self.lb, self.ub - self.A@x + + +class Bounds: + """Bounds constraint on the variables. + + The constraint has the general inequality form:: + + lb <= x <= ub + + It is possible to use equal bounds to represent an equality constraint or + infinite bounds to represent a one-sided constraint. + + Parameters + ---------- + lb, ub : dense array_like, optional + Lower and upper bounds on independent variables. `lb`, `ub`, and + `keep_feasible` must be the same shape or broadcastable. + Set components of `lb` and `ub` equal + to fix a variable. Use ``np.inf`` with an appropriate sign to disable + bounds on all or some variables. Note that you can mix constraints of + different types: interval, one-sided or equality, by setting different + components of `lb` and `ub` as necessary. Defaults to ``lb = -np.inf`` + and ``ub = np.inf`` (no bounds). + keep_feasible : dense array_like of bool, optional + Whether to keep the constraint components feasible throughout + iterations. Must be broadcastable with `lb` and `ub`. + Default is False. Has no effect for equality constraints. + """ + def _input_validation(self): + try: + res = np.broadcast_arrays(self.lb, self.ub, self.keep_feasible) + self.lb, self.ub, self.keep_feasible = res + except ValueError: + message = "`lb`, `ub`, and `keep_feasible` must be broadcastable." + raise ValueError(message) + + def __init__(self, lb=-np.inf, ub=np.inf, keep_feasible=False): + if issparse(lb) or issparse(ub): + raise ValueError("Lower and upper bounds must be dense arrays.") + self.lb = np.atleast_1d(lb) + self.ub = np.atleast_1d(ub) + + if issparse(keep_feasible): + raise ValueError("`keep_feasible` must be a dense array.") + self.keep_feasible = np.atleast_1d(keep_feasible).astype(bool) + self._input_validation() + + def __repr__(self): + start = f"{type(self).__name__}({self.lb!r}, {self.ub!r}" + if np.any(self.keep_feasible): + end = f", keep_feasible={self.keep_feasible!r})" + else: + end = ")" + return start + end + + def residual(self, x): + """Calculate the residual (slack) between the input and the bounds + + For a bound constraint of the form:: + + lb <= x <= ub + + the lower and upper residuals between `x` and the bounds are values + ``sl`` and ``sb`` such that:: + + lb + sl == x == ub - sb + + When all elements of ``sl`` and ``sb`` are positive, all elements of + ``x`` lie within the bounds; a negative element in ``sl`` or ``sb`` + indicates that the corresponding element of ``x`` is out of bounds. + + Parameters + ---------- + x: array_like + Vector of independent variables + + Returns + ------- + sl, sb : array-like + The lower and upper residuals + """ + return x - self.lb, self.ub - x + + +class PreparedConstraint: + """Constraint prepared from a user defined constraint. + + On creation it will check whether a constraint definition is valid and + the initial point is feasible. If created successfully, it will contain + the attributes listed below. + + Parameters + ---------- + constraint : {NonlinearConstraint, LinearConstraint`, Bounds} + Constraint to check and prepare. + x0 : array_like + Initial vector of independent variables. + sparse_jacobian : bool or None, optional + If bool, then the Jacobian of the constraint will be converted + to the corresponded format if necessary. If None (default), such + conversion is not made. + finite_diff_bounds : 2-tuple, optional + Lower and upper bounds on the independent variables for the finite + difference approximation, if applicable. Defaults to no bounds. + + Attributes + ---------- + fun : {VectorFunction, LinearVectorFunction, IdentityVectorFunction} + Function defining the constraint wrapped by one of the convenience + classes. + bounds : 2-tuple + Contains lower and upper bounds for the constraints --- lb and ub. + These are converted to ndarray and have a size equal to the number of + the constraints. + keep_feasible : ndarray + Array indicating which components must be kept feasible with a size + equal to the number of the constraints. + """ + def __init__(self, constraint, x0, sparse_jacobian=None, + finite_diff_bounds=(-np.inf, np.inf)): + if isinstance(constraint, NonlinearConstraint): + fun = VectorFunction(constraint.fun, x0, + constraint.jac, constraint.hess, + constraint.finite_diff_rel_step, + constraint.finite_diff_jac_sparsity, + finite_diff_bounds, sparse_jacobian) + elif isinstance(constraint, LinearConstraint): + fun = LinearVectorFunction(constraint.A, x0, sparse_jacobian) + elif isinstance(constraint, Bounds): + fun = IdentityVectorFunction(x0, sparse_jacobian) + else: + raise ValueError("`constraint` of an unknown type is passed.") + + m = fun.m + + lb = np.asarray(constraint.lb, dtype=float) + ub = np.asarray(constraint.ub, dtype=float) + keep_feasible = np.asarray(constraint.keep_feasible, dtype=bool) + + lb = np.broadcast_to(lb, m) + ub = np.broadcast_to(ub, m) + keep_feasible = np.broadcast_to(keep_feasible, m) + + if keep_feasible.shape != (m,): + raise ValueError("`keep_feasible` has a wrong shape.") + + mask = keep_feasible & (lb != ub) + f0 = fun.f + if np.any(f0[mask] < lb[mask]) or np.any(f0[mask] > ub[mask]): + raise ValueError("`x0` is infeasible with respect to some " + "inequality constraint with `keep_feasible` " + "set to True.") + + self.fun = fun + self.bounds = (lb, ub) + self.keep_feasible = keep_feasible + + def violation(self, x): + """How much the constraint is exceeded by. + + Parameters + ---------- + x : array-like + Vector of independent variables + + Returns + ------- + excess : array-like + How much the constraint is exceeded by, for each of the + constraints specified by `PreparedConstraint.fun`. + """ + with catch_warnings(): + # Ignore the following warning, it's not important when + # figuring out total violation + # UserWarning: delta_grad == 0.0. Check if the approximated + # function is linear + filterwarnings("ignore", "delta_grad", UserWarning) + ev = self.fun.fun(np.asarray(x)) + + excess_lb = np.maximum(self.bounds[0] - ev, 0) + excess_ub = np.maximum(ev - self.bounds[1], 0) + + return excess_lb + excess_ub + + +def new_bounds_to_old(lb, ub, n): + """Convert the new bounds representation to the old one. + + The new representation is a tuple (lb, ub) and the old one is a list + containing n tuples, ith containing lower and upper bound on a ith + variable. + If any of the entries in lb/ub are -np.inf/np.inf they are replaced by + None. + """ + lb = np.broadcast_to(lb, n) + ub = np.broadcast_to(ub, n) + + lb = [float(x) if x > -np.inf else None for x in lb] + ub = [float(x) if x < np.inf else None for x in ub] + + return list(zip(lb, ub)) + + +def old_bound_to_new(bounds): + """Convert the old bounds representation to the new one. + + The new representation is a tuple (lb, ub) and the old one is a list + containing n tuples, ith containing lower and upper bound on a ith + variable. + If any of the entries in lb/ub are None they are replaced by + -np.inf/np.inf. + """ + lb, ub = zip(*bounds) + + # Convert occurrences of None to -inf or inf, and replace occurrences of + # any numpy array x with x.item(). Then wrap the results in numpy arrays. + lb = np.array([float(_arr_to_scalar(x)) if x is not None else -np.inf + for x in lb]) + ub = np.array([float(_arr_to_scalar(x)) if x is not None else np.inf + for x in ub]) + + return lb, ub + + +def strict_bounds(lb, ub, keep_feasible, n_vars): + """Remove bounds which are not asked to be kept feasible.""" + strict_lb = np.resize(lb, n_vars).astype(float) + strict_ub = np.resize(ub, n_vars).astype(float) + keep_feasible = np.resize(keep_feasible, n_vars) + strict_lb[~keep_feasible] = -np.inf + strict_ub[~keep_feasible] = np.inf + return strict_lb, strict_ub + + +def new_constraint_to_old(con, x0): + """ + Converts new-style constraint objects to old-style constraint dictionaries. + """ + if isinstance(con, NonlinearConstraint): + if (con.finite_diff_jac_sparsity is not None or + con.finite_diff_rel_step is not None or + not isinstance(con.hess, BFGS) or # misses user specified BFGS + con.keep_feasible): + warn("Constraint options `finite_diff_jac_sparsity`, " + "`finite_diff_rel_step`, `keep_feasible`, and `hess`" + "are ignored by this method.", + OptimizeWarning, stacklevel=3) + + fun = con.fun + if callable(con.jac): + jac = con.jac + else: + jac = None + + else: # LinearConstraint + if np.any(con.keep_feasible): + warn("Constraint option `keep_feasible` is ignored by this method.", + OptimizeWarning, stacklevel=3) + + A = con.A + if issparse(A): + A = A.toarray() + def fun(x): + return np.dot(A, x) + def jac(x): + return A + + # FIXME: when bugs in VectorFunction/LinearVectorFunction are worked out, + # use pcon.fun.fun and pcon.fun.jac. Until then, get fun/jac above. + pcon = PreparedConstraint(con, x0) + lb, ub = pcon.bounds + + i_eq = lb == ub + i_bound_below = np.logical_xor(lb != -np.inf, i_eq) + i_bound_above = np.logical_xor(ub != np.inf, i_eq) + i_unbounded = np.logical_and(lb == -np.inf, ub == np.inf) + + if np.any(i_unbounded): + warn("At least one constraint is unbounded above and below. Such " + "constraints are ignored.", + OptimizeWarning, stacklevel=3) + + ceq = [] + if np.any(i_eq): + def f_eq(x): + y = np.array(fun(x)).flatten() + return y[i_eq] - lb[i_eq] + ceq = [{"type": "eq", "fun": f_eq}] + + if jac is not None: + def j_eq(x): + dy = jac(x) + if issparse(dy): + dy = dy.toarray() + dy = np.atleast_2d(dy) + return dy[i_eq, :] + ceq[0]["jac"] = j_eq + + cineq = [] + n_bound_below = np.sum(i_bound_below) + n_bound_above = np.sum(i_bound_above) + if n_bound_below + n_bound_above: + def f_ineq(x): + y = np.zeros(n_bound_below + n_bound_above) + y_all = np.array(fun(x)).flatten() + y[:n_bound_below] = y_all[i_bound_below] - lb[i_bound_below] + y[n_bound_below:] = -(y_all[i_bound_above] - ub[i_bound_above]) + return y + cineq = [{"type": "ineq", "fun": f_ineq}] + + if jac is not None: + def j_ineq(x): + dy = np.zeros((n_bound_below + n_bound_above, len(x0))) + dy_all = jac(x) + if issparse(dy_all): + dy_all = dy_all.toarray() + dy_all = np.atleast_2d(dy_all) + dy[:n_bound_below, :] = dy_all[i_bound_below] + dy[n_bound_below:, :] = -dy_all[i_bound_above] + return dy + cineq[0]["jac"] = j_ineq + + old_constraints = ceq + cineq + + if len(old_constraints) > 1: + warn("Equality and inequality constraints are specified in the same " + "element of the constraint list. For efficient use with this " + "method, equality and inequality constraints should be specified " + "in separate elements of the constraint list. ", + OptimizeWarning, stacklevel=3) + return old_constraints + + +def old_constraint_to_new(ic, con): + """ + Converts old-style constraint dictionaries to new-style constraint objects. + """ + # check type + try: + ctype = con['type'].lower() + except KeyError as e: + raise KeyError('Constraint %d has no type defined.' % ic) from e + except TypeError as e: + raise TypeError( + 'Constraints must be a sequence of dictionaries.' + ) from e + except AttributeError as e: + raise TypeError("Constraint's type must be a string.") from e + else: + if ctype not in ['eq', 'ineq']: + raise ValueError("Unknown constraint type '%s'." % con['type']) + if 'fun' not in con: + raise ValueError('Constraint %d has no function defined.' % ic) + + lb = 0 + if ctype == 'eq': + ub = 0 + else: + ub = np.inf + + jac = '2-point' + if 'args' in con: + args = con['args'] + def fun(x): + return con["fun"](x, *args) + if 'jac' in con: + def jac(x): + return con["jac"](x, *args) + else: + fun = con['fun'] + if 'jac' in con: + jac = con['jac'] + + return NonlinearConstraint(fun, lb, ub, jac) diff --git a/llava_next/lib/python3.10/site-packages/scipy/optimize/_dcsrch.py b/llava_next/lib/python3.10/site-packages/scipy/optimize/_dcsrch.py new file mode 100644 index 0000000000000000000000000000000000000000..f8b4df4763ba4f699869431a0b6528383c2f0328 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/scipy/optimize/_dcsrch.py @@ -0,0 +1,728 @@ +import numpy as np + +""" +# 2023 - ported from minpack2.dcsrch, dcstep (Fortran) to Python +c MINPACK-1 Project. June 1983. +c Argonne National Laboratory. +c Jorge J. More' and David J. Thuente. +c +c MINPACK-2 Project. November 1993. +c Argonne National Laboratory and University of Minnesota. +c Brett M. Averick, Richard G. Carter, and Jorge J. More'. +""" + +# NOTE this file was linted by black on first commit, and can be kept that way. + + +class DCSRCH: + """ + Parameters + ---------- + phi : callable phi(alpha) + Function at point `alpha` + derphi : callable phi'(alpha) + Objective function derivative. Returns a scalar. + ftol : float + A nonnegative tolerance for the sufficient decrease condition. + gtol : float + A nonnegative tolerance for the curvature condition. + xtol : float + A nonnegative relative tolerance for an acceptable step. The + subroutine exits with a warning if the relative difference between + sty and stx is less than xtol. + stpmin : float + A nonnegative lower bound for the step. + stpmax : + A nonnegative upper bound for the step. + + Notes + ----- + + This subroutine finds a step that satisfies a sufficient + decrease condition and a curvature condition. + + Each call of the subroutine updates an interval with + endpoints stx and sty. The interval is initially chosen + so that it contains a minimizer of the modified function + + psi(stp) = f(stp) - f(0) - ftol*stp*f'(0). + + If psi(stp) <= 0 and f'(stp) >= 0 for some step, then the + interval is chosen so that it contains a minimizer of f. + + The algorithm is designed to find a step that satisfies + the sufficient decrease condition + + f(stp) <= f(0) + ftol*stp*f'(0), + + and the curvature condition + + abs(f'(stp)) <= gtol*abs(f'(0)). + + If ftol is less than gtol and if, for example, the function + is bounded below, then there is always a step which satisfies + both conditions. + + If no step can be found that satisfies both conditions, then + the algorithm stops with a warning. In this case stp only + satisfies the sufficient decrease condition. + + A typical invocation of dcsrch has the following outline: + + Evaluate the function at stp = 0.0d0; store in f. + Evaluate the gradient at stp = 0.0d0; store in g. + Choose a starting step stp. + + task = 'START' + 10 continue + call dcsrch(stp,f,g,ftol,gtol,xtol,task,stpmin,stpmax, + isave,dsave) + if (task .eq. 'FG') then + Evaluate the function and the gradient at stp + go to 10 + end if + + NOTE: The user must not alter work arrays between calls. + + The subroutine statement is + + subroutine dcsrch(f,g,stp,ftol,gtol,xtol,stpmin,stpmax, + task,isave,dsave) + where + + stp is a double precision variable. + On entry stp is the current estimate of a satisfactory + step. On initial entry, a positive initial estimate + must be provided. + On exit stp is the current estimate of a satisfactory step + if task = 'FG'. If task = 'CONV' then stp satisfies + the sufficient decrease and curvature condition. + + f is a double precision variable. + On initial entry f is the value of the function at 0. + On subsequent entries f is the value of the + function at stp. + On exit f is the value of the function at stp. + + g is a double precision variable. + On initial entry g is the derivative of the function at 0. + On subsequent entries g is the derivative of the + function at stp. + On exit g is the derivative of the function at stp. + + ftol is a double precision variable. + On entry ftol specifies a nonnegative tolerance for the + sufficient decrease condition. + On exit ftol is unchanged. + + gtol is a double precision variable. + On entry gtol specifies a nonnegative tolerance for the + curvature condition. + On exit gtol is unchanged. + + xtol is a double precision variable. + On entry xtol specifies a nonnegative relative tolerance + for an acceptable step. The subroutine exits with a + warning if the relative difference between sty and stx + is less than xtol. + + On exit xtol is unchanged. + + task is a character variable of length at least 60. + On initial entry task must be set to 'START'. + On exit task indicates the required action: + + If task(1:2) = 'FG' then evaluate the function and + derivative at stp and call dcsrch again. + + If task(1:4) = 'CONV' then the search is successful. + + If task(1:4) = 'WARN' then the subroutine is not able + to satisfy the convergence conditions. The exit value of + stp contains the best point found during the search. + + If task(1:5) = 'ERROR' then there is an error in the + input arguments. + + On exit with convergence, a warning or an error, the + variable task contains additional information. + + stpmin is a double precision variable. + On entry stpmin is a nonnegative lower bound for the step. + On exit stpmin is unchanged. + + stpmax is a double precision variable. + On entry stpmax is a nonnegative upper bound for the step. + On exit stpmax is unchanged. + + isave is an integer work array of dimension 2. + + dsave is a double precision work array of dimension 13. + + Subprograms called + + MINPACK-2 ... dcstep + MINPACK-1 Project. June 1983. + Argonne National Laboratory. + Jorge J. More' and David J. Thuente. + + MINPACK-2 Project. November 1993. + Argonne National Laboratory and University of Minnesota. + Brett M. Averick, Richard G. Carter, and Jorge J. More'. + """ + + def __init__(self, phi, derphi, ftol, gtol, xtol, stpmin, stpmax): + self.stage = None + self.ginit = None + self.gtest = None + self.gx = None + self.gy = None + self.finit = None + self.fx = None + self.fy = None + self.stx = None + self.sty = None + self.stmin = None + self.stmax = None + self.width = None + self.width1 = None + + # leave all assessment of tolerances/limits to the first call of + # this object + self.ftol = ftol + self.gtol = gtol + self.xtol = xtol + self.stpmin = stpmin + self.stpmax = stpmax + + self.phi = phi + self.derphi = derphi + + def __call__(self, alpha1, phi0=None, derphi0=None, maxiter=100): + """ + Parameters + ---------- + alpha1 : float + alpha1 is the current estimate of a satisfactory + step. A positive initial estimate must be provided. + phi0 : float + the value of `phi` at 0 (if known). + derphi0 : float + the derivative of `derphi` at 0 (if known). + maxiter : int + + Returns + ------- + alpha : float + Step size, or None if no suitable step was found. + phi : float + Value of `phi` at the new point `alpha`. + phi0 : float + Value of `phi` at `alpha=0`. + task : bytes + On exit task indicates status information. + + If task[:4] == b'CONV' then the search is successful. + + If task[:4] == b'WARN' then the subroutine is not able + to satisfy the convergence conditions. The exit value of + stp contains the best point found during the search. + + If task[:5] == b'ERROR' then there is an error in the + input arguments. + """ + if phi0 is None: + phi0 = self.phi(0.0) + if derphi0 is None: + derphi0 = self.derphi(0.0) + + phi1 = phi0 + derphi1 = derphi0 + + task = b"START" + for i in range(maxiter): + stp, phi1, derphi1, task = self._iterate( + alpha1, phi1, derphi1, task + ) + + if not np.isfinite(stp): + task = b"WARN" + stp = None + break + + if task[:2] == b"FG": + alpha1 = stp + phi1 = self.phi(stp) + derphi1 = self.derphi(stp) + else: + break + else: + # maxiter reached, the line search did not converge + stp = None + task = b"WARNING: dcsrch did not converge within max iterations" + + if task[:5] == b"ERROR" or task[:4] == b"WARN": + stp = None # failed + + return stp, phi1, phi0, task + + def _iterate(self, stp, f, g, task): + """ + Parameters + ---------- + stp : float + The current estimate of a satisfactory step. On initial entry, a + positive initial estimate must be provided. + f : float + On first call f is the value of the function at 0. On subsequent + entries f should be the value of the function at stp. + g : float + On initial entry g is the derivative of the function at 0. On + subsequent entries g is the derivative of the function at stp. + task : bytes + On initial entry task must be set to 'START'. + + On exit with convergence, a warning or an error, the + variable task contains additional information. + + + Returns + ------- + stp, f, g, task: tuple + + stp : float + the current estimate of a satisfactory step if task = 'FG'. If + task = 'CONV' then stp satisfies the sufficient decrease and + curvature condition. + f : float + the value of the function at stp. + g : float + the derivative of the function at stp. + task : bytes + On exit task indicates the required action: + + If task(1:2) == b'FG' then evaluate the function and + derivative at stp and call dcsrch again. + + If task(1:4) == b'CONV' then the search is successful. + + If task(1:4) == b'WARN' then the subroutine is not able + to satisfy the convergence conditions. The exit value of + stp contains the best point found during the search. + + If task(1:5) == b'ERROR' then there is an error in the + input arguments. + """ + p5 = 0.5 + p66 = 0.66 + xtrapl = 1.1 + xtrapu = 4.0 + + if task[:5] == b"START": + if stp < self.stpmin: + task = b"ERROR: STP .LT. STPMIN" + if stp > self.stpmax: + task = b"ERROR: STP .GT. STPMAX" + if g >= 0: + task = b"ERROR: INITIAL G .GE. ZERO" + if self.ftol < 0: + task = b"ERROR: FTOL .LT. ZERO" + if self.gtol < 0: + task = b"ERROR: GTOL .LT. ZERO" + if self.xtol < 0: + task = b"ERROR: XTOL .LT. ZERO" + if self.stpmin < 0: + task = b"ERROR: STPMIN .LT. ZERO" + if self.stpmax < self.stpmin: + task = b"ERROR: STPMAX .LT. STPMIN" + + if task[:5] == b"ERROR": + return stp, f, g, task + + # Initialize local variables. + + self.brackt = False + self.stage = 1 + self.finit = f + self.ginit = g + self.gtest = self.ftol * self.ginit + self.width = self.stpmax - self.stpmin + self.width1 = self.width / p5 + + # The variables stx, fx, gx contain the values of the step, + # function, and derivative at the best step. + # The variables sty, fy, gy contain the value of the step, + # function, and derivative at sty. + # The variables stp, f, g contain the values of the step, + # function, and derivative at stp. + + self.stx = 0.0 + self.fx = self.finit + self.gx = self.ginit + self.sty = 0.0 + self.fy = self.finit + self.gy = self.ginit + self.stmin = 0 + self.stmax = stp + xtrapu * stp + task = b"FG" + return stp, f, g, task + + # in the original Fortran this was a location to restore variables + # we don't need to do that because they're attributes. + + # If psi(stp) <= 0 and f'(stp) >= 0 for some step, then the + # algorithm enters the second stage. + ftest = self.finit + stp * self.gtest + + if self.stage == 1 and f <= ftest and g >= 0: + self.stage = 2 + + # test for warnings + if self.brackt and (stp <= self.stmin or stp >= self.stmax): + task = b"WARNING: ROUNDING ERRORS PREVENT PROGRESS" + if self.brackt and self.stmax - self.stmin <= self.xtol * self.stmax: + task = b"WARNING: XTOL TEST SATISFIED" + if stp == self.stpmax and f <= ftest and g <= self.gtest: + task = b"WARNING: STP = STPMAX" + if stp == self.stpmin and (f > ftest or g >= self.gtest): + task = b"WARNING: STP = STPMIN" + + # test for convergence + if f <= ftest and abs(g) <= self.gtol * -self.ginit: + task = b"CONVERGENCE" + + # test for termination + if task[:4] == b"WARN" or task[:4] == b"CONV": + return stp, f, g, task + + # A modified function is used to predict the step during the + # first stage if a lower function value has been obtained but + # the decrease is not sufficient. + if self.stage == 1 and f <= self.fx and f > ftest: + # Define the modified function and derivative values. + fm = f - stp * self.gtest + fxm = self.fx - self.stx * self.gtest + fym = self.fy - self.sty * self.gtest + gm = g - self.gtest + gxm = self.gx - self.gtest + gym = self.gy - self.gtest + + # Call dcstep to update stx, sty, and to compute the new step. + # dcstep can have several operations which can produce NaN + # e.g. inf/inf. Filter these out. + with np.errstate(invalid="ignore", over="ignore"): + tup = dcstep( + self.stx, + fxm, + gxm, + self.sty, + fym, + gym, + stp, + fm, + gm, + self.brackt, + self.stmin, + self.stmax, + ) + self.stx, fxm, gxm, self.sty, fym, gym, stp, self.brackt = tup + + # Reset the function and derivative values for f + self.fx = fxm + self.stx * self.gtest + self.fy = fym + self.sty * self.gtest + self.gx = gxm + self.gtest + self.gy = gym + self.gtest + + else: + # Call dcstep to update stx, sty, and to compute the new step. + # dcstep can have several operations which can produce NaN + # e.g. inf/inf. Filter these out. + + with np.errstate(invalid="ignore", over="ignore"): + tup = dcstep( + self.stx, + self.fx, + self.gx, + self.sty, + self.fy, + self.gy, + stp, + f, + g, + self.brackt, + self.stmin, + self.stmax, + ) + ( + self.stx, + self.fx, + self.gx, + self.sty, + self.fy, + self.gy, + stp, + self.brackt, + ) = tup + + # Decide if a bisection step is needed + if self.brackt: + if abs(self.sty - self.stx) >= p66 * self.width1: + stp = self.stx + p5 * (self.sty - self.stx) + self.width1 = self.width + self.width = abs(self.sty - self.stx) + + # Set the minimum and maximum steps allowed for stp. + if self.brackt: + self.stmin = min(self.stx, self.sty) + self.stmax = max(self.stx, self.sty) + else: + self.stmin = stp + xtrapl * (stp - self.stx) + self.stmax = stp + xtrapu * (stp - self.stx) + + # Force the step to be within the bounds stpmax and stpmin. + stp = np.clip(stp, self.stpmin, self.stpmax) + + # If further progress is not possible, let stp be the best + # point obtained during the search. + if ( + self.brackt + and (stp <= self.stmin or stp >= self.stmax) + or ( + self.brackt + and self.stmax - self.stmin <= self.xtol * self.stmax + ) + ): + stp = self.stx + + # Obtain another function and derivative + task = b"FG" + return stp, f, g, task + + +def dcstep(stx, fx, dx, sty, fy, dy, stp, fp, dp, brackt, stpmin, stpmax): + """ + Subroutine dcstep + + This subroutine computes a safeguarded step for a search + procedure and updates an interval that contains a step that + satisfies a sufficient decrease and a curvature condition. + + The parameter stx contains the step with the least function + value. If brackt is set to .true. then a minimizer has + been bracketed in an interval with endpoints stx and sty. + The parameter stp contains the current step. + The subroutine assumes that if brackt is set to .true. then + + min(stx,sty) < stp < max(stx,sty), + + and that the derivative at stx is negative in the direction + of the step. + + The subroutine statement is + + subroutine dcstep(stx,fx,dx,sty,fy,dy,stp,fp,dp,brackt, + stpmin,stpmax) + + where + + stx is a double precision variable. + On entry stx is the best step obtained so far and is an + endpoint of the interval that contains the minimizer. + On exit stx is the updated best step. + + fx is a double precision variable. + On entry fx is the function at stx. + On exit fx is the function at stx. + + dx is a double precision variable. + On entry dx is the derivative of the function at + stx. The derivative must be negative in the direction of + the step, that is, dx and stp - stx must have opposite + signs. + On exit dx is the derivative of the function at stx. + + sty is a double precision variable. + On entry sty is the second endpoint of the interval that + contains the minimizer. + On exit sty is the updated endpoint of the interval that + contains the minimizer. + + fy is a double precision variable. + On entry fy is the function at sty. + On exit fy is the function at sty. + + dy is a double precision variable. + On entry dy is the derivative of the function at sty. + On exit dy is the derivative of the function at the exit sty. + + stp is a double precision variable. + On entry stp is the current step. If brackt is set to .true. + then on input stp must be between stx and sty. + On exit stp is a new trial step. + + fp is a double precision variable. + On entry fp is the function at stp + On exit fp is unchanged. + + dp is a double precision variable. + On entry dp is the derivative of the function at stp. + On exit dp is unchanged. + + brackt is an logical variable. + On entry brackt specifies if a minimizer has been bracketed. + Initially brackt must be set to .false. + On exit brackt specifies if a minimizer has been bracketed. + When a minimizer is bracketed brackt is set to .true. + + stpmin is a double precision variable. + On entry stpmin is a lower bound for the step. + On exit stpmin is unchanged. + + stpmax is a double precision variable. + On entry stpmax is an upper bound for the step. + On exit stpmax is unchanged. + + MINPACK-1 Project. June 1983 + Argonne National Laboratory. + Jorge J. More' and David J. Thuente. + + MINPACK-2 Project. November 1993. + Argonne National Laboratory and University of Minnesota. + Brett M. Averick and Jorge J. More'. + + """ + sgn_dp = np.sign(dp) + sgn_dx = np.sign(dx) + + # sgnd = dp * (dx / abs(dx)) + sgnd = sgn_dp * sgn_dx + + # First case: A higher function value. The minimum is bracketed. + # If the cubic step is closer to stx than the quadratic step, the + # cubic step is taken, otherwise the average of the cubic and + # quadratic steps is taken. + if fp > fx: + theta = 3.0 * (fx - fp) / (stp - stx) + dx + dp + s = max(abs(theta), abs(dx), abs(dp)) + gamma = s * np.sqrt((theta / s) ** 2 - (dx / s) * (dp / s)) + if stp < stx: + gamma *= -1 + p = (gamma - dx) + theta + q = ((gamma - dx) + gamma) + dp + r = p / q + stpc = stx + r * (stp - stx) + stpq = stx + ((dx / ((fx - fp) / (stp - stx) + dx)) / 2.0) * (stp - stx) + if abs(stpc - stx) <= abs(stpq - stx): + stpf = stpc + else: + stpf = stpc + (stpq - stpc) / 2.0 + brackt = True + elif sgnd < 0.0: + # Second case: A lower function value and derivatives of opposite + # sign. The minimum is bracketed. If the cubic step is farther from + # stp than the secant step, the cubic step is taken, otherwise the + # secant step is taken. + theta = 3 * (fx - fp) / (stp - stx) + dx + dp + s = max(abs(theta), abs(dx), abs(dp)) + gamma = s * np.sqrt((theta / s) ** 2 - (dx / s) * (dp / s)) + if stp > stx: + gamma *= -1 + p = (gamma - dp) + theta + q = ((gamma - dp) + gamma) + dx + r = p / q + stpc = stp + r * (stx - stp) + stpq = stp + (dp / (dp - dx)) * (stx - stp) + if abs(stpc - stp) > abs(stpq - stp): + stpf = stpc + else: + stpf = stpq + brackt = True + elif abs(dp) < abs(dx): + # Third case: A lower function value, derivatives of the same sign, + # and the magnitude of the derivative decreases. + + # The cubic step is computed only if the cubic tends to infinity + # in the direction of the step or if the minimum of the cubic + # is beyond stp. Otherwise the cubic step is defined to be the + # secant step. + theta = 3 * (fx - fp) / (stp - stx) + dx + dp + s = max(abs(theta), abs(dx), abs(dp)) + + # The case gamma = 0 only arises if the cubic does not tend + # to infinity in the direction of the step. + gamma = s * np.sqrt(max(0, (theta / s) ** 2 - (dx / s) * (dp / s))) + if stp > stx: + gamma = -gamma + p = (gamma - dp) + theta + q = (gamma + (dx - dp)) + gamma + r = p / q + if r < 0 and gamma != 0: + stpc = stp + r * (stx - stp) + elif stp > stx: + stpc = stpmax + else: + stpc = stpmin + stpq = stp + (dp / (dp - dx)) * (stx - stp) + + if brackt: + # A minimizer has been bracketed. If the cubic step is + # closer to stp than the secant step, the cubic step is + # taken, otherwise the secant step is taken. + if abs(stpc - stp) < abs(stpq - stp): + stpf = stpc + else: + stpf = stpq + + if stp > stx: + stpf = min(stp + 0.66 * (sty - stp), stpf) + else: + stpf = max(stp + 0.66 * (sty - stp), stpf) + else: + # A minimizer has not been bracketed. If the cubic step is + # farther from stp than the secant step, the cubic step is + # taken, otherwise the secant step is taken. + if abs(stpc - stp) > abs(stpq - stp): + stpf = stpc + else: + stpf = stpq + stpf = np.clip(stpf, stpmin, stpmax) + + else: + # Fourth case: A lower function value, derivatives of the same sign, + # and the magnitude of the derivative does not decrease. If the + # minimum is not bracketed, the step is either stpmin or stpmax, + # otherwise the cubic step is taken. + if brackt: + theta = 3.0 * (fp - fy) / (sty - stp) + dy + dp + s = max(abs(theta), abs(dy), abs(dp)) + gamma = s * np.sqrt((theta / s) ** 2 - (dy / s) * (dp / s)) + if stp > sty: + gamma = -gamma + p = (gamma - dp) + theta + q = ((gamma - dp) + gamma) + dy + r = p / q + stpc = stp + r * (sty - stp) + stpf = stpc + elif stp > stx: + stpf = stpmax + else: + stpf = stpmin + + # Update the interval which contains a minimizer. + if fp > fx: + sty = stp + fy = fp + dy = dp + else: + if sgnd < 0: + sty = stx + fy = fx + dy = dx + stx = stp + fx = fp + dx = dp + + # Compute the new step. + stp = stpf + + return stx, fx, dx, sty, fy, dy, stp, brackt diff --git a/llava_next/lib/python3.10/site-packages/scipy/optimize/_differentiable_functions.py b/llava_next/lib/python3.10/site-packages/scipy/optimize/_differentiable_functions.py new file mode 100644 index 0000000000000000000000000000000000000000..9370aff56f7dd428ecb56af31e21f8a5fa181bb4 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/scipy/optimize/_differentiable_functions.py @@ -0,0 +1,693 @@ +import numpy as np +import scipy.sparse as sps +from ._numdiff import approx_derivative, group_columns +from ._hessian_update_strategy import HessianUpdateStrategy +from scipy.sparse.linalg import LinearOperator +from scipy._lib._array_api import atleast_nd, array_namespace + + +FD_METHODS = ('2-point', '3-point', 'cs') + + +def _wrapper_fun(fun, args=()): + ncalls = [0] + + def wrapped(x): + ncalls[0] += 1 + # Send a copy because the user may overwrite it. + # Overwriting results in undefined behaviour because + # fun(self.x) will change self.x, with the two no longer linked. + fx = fun(np.copy(x), *args) + # Make sure the function returns a true scalar + if not np.isscalar(fx): + try: + fx = np.asarray(fx).item() + except (TypeError, ValueError) as e: + raise ValueError( + "The user-provided objective function " + "must return a scalar value." + ) from e + return fx + return wrapped, ncalls + + +def _wrapper_grad(grad, fun=None, args=(), finite_diff_options=None): + ncalls = [0] + + if callable(grad): + def wrapped(x, **kwds): + # kwds present to give function same signature as numdiff variant + ncalls[0] += 1 + return np.atleast_1d(grad(np.copy(x), *args)) + return wrapped, ncalls + + elif grad in FD_METHODS: + def wrapped1(x, f0=None): + ncalls[0] += 1 + return approx_derivative( + fun, x, f0=f0, **finite_diff_options + ) + + return wrapped1, ncalls + + +def _wrapper_hess(hess, grad=None, x0=None, args=(), finite_diff_options=None): + if callable(hess): + H = hess(np.copy(x0), *args) + ncalls = [1] + + if sps.issparse(H): + def wrapped(x, **kwds): + ncalls[0] += 1 + return sps.csr_matrix(hess(np.copy(x), *args)) + + H = sps.csr_matrix(H) + + elif isinstance(H, LinearOperator): + def wrapped(x, **kwds): + ncalls[0] += 1 + return hess(np.copy(x), *args) + + else: # dense + def wrapped(x, **kwds): + ncalls[0] += 1 + return np.atleast_2d(np.asarray(hess(np.copy(x), *args))) + + H = np.atleast_2d(np.asarray(H)) + + return wrapped, ncalls, H + elif hess in FD_METHODS: + ncalls = [0] + + def wrapped1(x, f0=None): + return approx_derivative( + grad, x, f0=f0, **finite_diff_options + ) + + return wrapped1, ncalls, None + + +class ScalarFunction: + """Scalar function and its derivatives. + + This class defines a scalar function F: R^n->R and methods for + computing or approximating its first and second derivatives. + + Parameters + ---------- + fun : callable + evaluates the scalar function. Must be of the form ``fun(x, *args)``, + where ``x`` is the argument in the form of a 1-D array and ``args`` is + a tuple of any additional fixed parameters needed to completely specify + the function. Should return a scalar. + x0 : array-like + Provides an initial set of variables for evaluating fun. Array of real + elements of size (n,), where 'n' is the number of independent + variables. + args : tuple, optional + Any additional fixed parameters needed to completely specify the scalar + function. + grad : {callable, '2-point', '3-point', 'cs'} + Method for computing the gradient vector. + If it is a callable, it should be a function that returns the gradient + vector: + + ``grad(x, *args) -> array_like, shape (n,)`` + + where ``x`` is an array with shape (n,) and ``args`` is a tuple with + the fixed parameters. + Alternatively, the keywords {'2-point', '3-point', 'cs'} can be used + to select a finite difference scheme for numerical estimation of the + gradient with a relative step size. These finite difference schemes + obey any specified `bounds`. + hess : {callable, '2-point', '3-point', 'cs', HessianUpdateStrategy} + Method for computing the Hessian matrix. If it is callable, it should + return the Hessian matrix: + + ``hess(x, *args) -> {LinearOperator, spmatrix, array}, (n, n)`` + + where x is a (n,) ndarray and `args` is a tuple with the fixed + parameters. Alternatively, the keywords {'2-point', '3-point', 'cs'} + select a finite difference scheme for numerical estimation. Or, objects + implementing `HessianUpdateStrategy` interface can be used to + approximate the Hessian. + Whenever the gradient is estimated via finite-differences, the Hessian + cannot be estimated with options {'2-point', '3-point', 'cs'} and needs + to be estimated using one of the quasi-Newton strategies. + finite_diff_rel_step : None or array_like + Relative step size to use. The absolute step size is computed as + ``h = finite_diff_rel_step * sign(x0) * max(1, abs(x0))``, possibly + adjusted to fit into the bounds. For ``method='3-point'`` the sign + of `h` is ignored. If None then finite_diff_rel_step is selected + automatically, + finite_diff_bounds : tuple of array_like + Lower and upper bounds on independent variables. Defaults to no bounds, + (-np.inf, np.inf). Each bound must match the size of `x0` or be a + scalar, in the latter case the bound will be the same for all + variables. Use it to limit the range of function evaluation. + epsilon : None or array_like, optional + Absolute step size to use, possibly adjusted to fit into the bounds. + For ``method='3-point'`` the sign of `epsilon` is ignored. By default + relative steps are used, only if ``epsilon is not None`` are absolute + steps used. + + Notes + ----- + This class implements a memoization logic. There are methods `fun`, + `grad`, hess` and corresponding attributes `f`, `g` and `H`. The following + things should be considered: + + 1. Use only public methods `fun`, `grad` and `hess`. + 2. After one of the methods is called, the corresponding attribute + will be set. However, a subsequent call with a different argument + of *any* of the methods may overwrite the attribute. + """ + def __init__(self, fun, x0, args, grad, hess, finite_diff_rel_step, + finite_diff_bounds, epsilon=None): + if not callable(grad) and grad not in FD_METHODS: + raise ValueError( + f"`grad` must be either callable or one of {FD_METHODS}." + ) + + if not (callable(hess) or hess in FD_METHODS + or isinstance(hess, HessianUpdateStrategy)): + raise ValueError( + f"`hess` must be either callable, HessianUpdateStrategy" + f" or one of {FD_METHODS}." + ) + + if grad in FD_METHODS and hess in FD_METHODS: + raise ValueError("Whenever the gradient is estimated via " + "finite-differences, we require the Hessian " + "to be estimated using one of the " + "quasi-Newton strategies.") + + self.xp = xp = array_namespace(x0) + _x = atleast_nd(x0, ndim=1, xp=xp) + _dtype = xp.float64 + if xp.isdtype(_x.dtype, "real floating"): + _dtype = _x.dtype + + # original arguments + self._wrapped_fun, self._nfev = _wrapper_fun(fun, args=args) + self._orig_fun = fun + self._orig_grad = grad + self._orig_hess = hess + self._args = args + + # promotes to floating + self.x = xp.astype(_x, _dtype) + self.x_dtype = _dtype + self.n = self.x.size + self.f_updated = False + self.g_updated = False + self.H_updated = False + + self._lowest_x = None + self._lowest_f = np.inf + + finite_diff_options = {} + if grad in FD_METHODS: + finite_diff_options["method"] = grad + finite_diff_options["rel_step"] = finite_diff_rel_step + finite_diff_options["abs_step"] = epsilon + finite_diff_options["bounds"] = finite_diff_bounds + if hess in FD_METHODS: + finite_diff_options["method"] = hess + finite_diff_options["rel_step"] = finite_diff_rel_step + finite_diff_options["abs_step"] = epsilon + finite_diff_options["as_linear_operator"] = True + + # Initial function evaluation + self._update_fun() + + # Initial gradient evaluation + self._wrapped_grad, self._ngev = _wrapper_grad( + grad, + fun=self._wrapped_fun, + args=args, + finite_diff_options=finite_diff_options + ) + self._update_grad() + + # Hessian evaluation + if callable(hess): + self._wrapped_hess, self._nhev, self.H = _wrapper_hess( + hess, x0=x0, args=args + ) + self.H_updated = True + elif hess in FD_METHODS: + self._wrapped_hess, self._nhev, self.H = _wrapper_hess( + hess, + grad=self._wrapped_grad, + x0=x0, + finite_diff_options=finite_diff_options + ) + self._update_grad() + self.H = self._wrapped_hess(self.x, f0=self.g) + self.H_updated = True + elif isinstance(hess, HessianUpdateStrategy): + self.H = hess + self.H.initialize(self.n, 'hess') + self.H_updated = True + self.x_prev = None + self.g_prev = None + self._nhev = [0] + + @property + def nfev(self): + return self._nfev[0] + + @property + def ngev(self): + return self._ngev[0] + + @property + def nhev(self): + return self._nhev[0] + + def _update_x(self, x): + if isinstance(self._orig_hess, HessianUpdateStrategy): + self._update_grad() + self.x_prev = self.x + self.g_prev = self.g + # ensure that self.x is a copy of x. Don't store a reference + # otherwise the memoization doesn't work properly. + + _x = atleast_nd(x, ndim=1, xp=self.xp) + self.x = self.xp.astype(_x, self.x_dtype) + self.f_updated = False + self.g_updated = False + self.H_updated = False + self._update_hess() + else: + # ensure that self.x is a copy of x. Don't store a reference + # otherwise the memoization doesn't work properly. + _x = atleast_nd(x, ndim=1, xp=self.xp) + self.x = self.xp.astype(_x, self.x_dtype) + self.f_updated = False + self.g_updated = False + self.H_updated = False + + def _update_fun(self): + if not self.f_updated: + fx = self._wrapped_fun(self.x) + if fx < self._lowest_f: + self._lowest_x = self.x + self._lowest_f = fx + + self.f = fx + self.f_updated = True + + def _update_grad(self): + if not self.g_updated: + if self._orig_grad in FD_METHODS: + self._update_fun() + self.g = self._wrapped_grad(self.x, f0=self.f) + self.g_updated = True + + def _update_hess(self): + if not self.H_updated: + if self._orig_hess in FD_METHODS: + self._update_grad() + self.H = self._wrapped_hess(self.x, f0=self.g) + elif isinstance(self._orig_hess, HessianUpdateStrategy): + self._update_grad() + self.H.update(self.x - self.x_prev, self.g - self.g_prev) + else: # should be callable(hess) + self.H = self._wrapped_hess(self.x) + + self.H_updated = True + + def fun(self, x): + if not np.array_equal(x, self.x): + self._update_x(x) + self._update_fun() + return self.f + + def grad(self, x): + if not np.array_equal(x, self.x): + self._update_x(x) + self._update_grad() + return self.g + + def hess(self, x): + if not np.array_equal(x, self.x): + self._update_x(x) + self._update_hess() + return self.H + + def fun_and_grad(self, x): + if not np.array_equal(x, self.x): + self._update_x(x) + self._update_fun() + self._update_grad() + return self.f, self.g + + +class VectorFunction: + """Vector function and its derivatives. + + This class defines a vector function F: R^n->R^m and methods for + computing or approximating its first and second derivatives. + + Notes + ----- + This class implements a memoization logic. There are methods `fun`, + `jac`, hess` and corresponding attributes `f`, `J` and `H`. The following + things should be considered: + + 1. Use only public methods `fun`, `jac` and `hess`. + 2. After one of the methods is called, the corresponding attribute + will be set. However, a subsequent call with a different argument + of *any* of the methods may overwrite the attribute. + """ + def __init__(self, fun, x0, jac, hess, + finite_diff_rel_step, finite_diff_jac_sparsity, + finite_diff_bounds, sparse_jacobian): + if not callable(jac) and jac not in FD_METHODS: + raise ValueError(f"`jac` must be either callable or one of {FD_METHODS}.") + + if not (callable(hess) or hess in FD_METHODS + or isinstance(hess, HessianUpdateStrategy)): + raise ValueError("`hess` must be either callable," + f"HessianUpdateStrategy or one of {FD_METHODS}.") + + if jac in FD_METHODS and hess in FD_METHODS: + raise ValueError("Whenever the Jacobian is estimated via " + "finite-differences, we require the Hessian to " + "be estimated using one of the quasi-Newton " + "strategies.") + + self.xp = xp = array_namespace(x0) + _x = atleast_nd(x0, ndim=1, xp=xp) + _dtype = xp.float64 + if xp.isdtype(_x.dtype, "real floating"): + _dtype = _x.dtype + + # promotes to floating + self.x = xp.astype(_x, _dtype) + self.x_dtype = _dtype + + self.n = self.x.size + self.nfev = 0 + self.njev = 0 + self.nhev = 0 + self.f_updated = False + self.J_updated = False + self.H_updated = False + + finite_diff_options = {} + if jac in FD_METHODS: + finite_diff_options["method"] = jac + finite_diff_options["rel_step"] = finite_diff_rel_step + if finite_diff_jac_sparsity is not None: + sparsity_groups = group_columns(finite_diff_jac_sparsity) + finite_diff_options["sparsity"] = (finite_diff_jac_sparsity, + sparsity_groups) + finite_diff_options["bounds"] = finite_diff_bounds + self.x_diff = np.copy(self.x) + if hess in FD_METHODS: + finite_diff_options["method"] = hess + finite_diff_options["rel_step"] = finite_diff_rel_step + finite_diff_options["as_linear_operator"] = True + self.x_diff = np.copy(self.x) + if jac in FD_METHODS and hess in FD_METHODS: + raise ValueError("Whenever the Jacobian is estimated via " + "finite-differences, we require the Hessian to " + "be estimated using one of the quasi-Newton " + "strategies.") + + # Function evaluation + def fun_wrapped(x): + self.nfev += 1 + return np.atleast_1d(fun(x)) + + def update_fun(): + self.f = fun_wrapped(self.x) + + self._update_fun_impl = update_fun + update_fun() + + self.v = np.zeros_like(self.f) + self.m = self.v.size + + # Jacobian Evaluation + if callable(jac): + self.J = jac(self.x) + self.J_updated = True + self.njev += 1 + + if (sparse_jacobian or + sparse_jacobian is None and sps.issparse(self.J)): + def jac_wrapped(x): + self.njev += 1 + return sps.csr_matrix(jac(x)) + self.J = sps.csr_matrix(self.J) + self.sparse_jacobian = True + + elif sps.issparse(self.J): + def jac_wrapped(x): + self.njev += 1 + return jac(x).toarray() + self.J = self.J.toarray() + self.sparse_jacobian = False + + else: + def jac_wrapped(x): + self.njev += 1 + return np.atleast_2d(jac(x)) + self.J = np.atleast_2d(self.J) + self.sparse_jacobian = False + + def update_jac(): + self.J = jac_wrapped(self.x) + + elif jac in FD_METHODS: + self.J = approx_derivative(fun_wrapped, self.x, f0=self.f, + **finite_diff_options) + self.J_updated = True + + if (sparse_jacobian or + sparse_jacobian is None and sps.issparse(self.J)): + def update_jac(): + self._update_fun() + self.J = sps.csr_matrix( + approx_derivative(fun_wrapped, self.x, f0=self.f, + **finite_diff_options)) + self.J = sps.csr_matrix(self.J) + self.sparse_jacobian = True + + elif sps.issparse(self.J): + def update_jac(): + self._update_fun() + self.J = approx_derivative(fun_wrapped, self.x, f0=self.f, + **finite_diff_options).toarray() + self.J = self.J.toarray() + self.sparse_jacobian = False + + else: + def update_jac(): + self._update_fun() + self.J = np.atleast_2d( + approx_derivative(fun_wrapped, self.x, f0=self.f, + **finite_diff_options)) + self.J = np.atleast_2d(self.J) + self.sparse_jacobian = False + + self._update_jac_impl = update_jac + + # Define Hessian + if callable(hess): + self.H = hess(self.x, self.v) + self.H_updated = True + self.nhev += 1 + + if sps.issparse(self.H): + def hess_wrapped(x, v): + self.nhev += 1 + return sps.csr_matrix(hess(x, v)) + self.H = sps.csr_matrix(self.H) + + elif isinstance(self.H, LinearOperator): + def hess_wrapped(x, v): + self.nhev += 1 + return hess(x, v) + + else: + def hess_wrapped(x, v): + self.nhev += 1 + return np.atleast_2d(np.asarray(hess(x, v))) + self.H = np.atleast_2d(np.asarray(self.H)) + + def update_hess(): + self.H = hess_wrapped(self.x, self.v) + elif hess in FD_METHODS: + def jac_dot_v(x, v): + return jac_wrapped(x).T.dot(v) + + def update_hess(): + self._update_jac() + self.H = approx_derivative(jac_dot_v, self.x, + f0=self.J.T.dot(self.v), + args=(self.v,), + **finite_diff_options) + update_hess() + self.H_updated = True + elif isinstance(hess, HessianUpdateStrategy): + self.H = hess + self.H.initialize(self.n, 'hess') + self.H_updated = True + self.x_prev = None + self.J_prev = None + + def update_hess(): + self._update_jac() + # When v is updated before x was updated, then x_prev and + # J_prev are None and we need this check. + if self.x_prev is not None and self.J_prev is not None: + delta_x = self.x - self.x_prev + delta_g = self.J.T.dot(self.v) - self.J_prev.T.dot(self.v) + self.H.update(delta_x, delta_g) + + self._update_hess_impl = update_hess + + if isinstance(hess, HessianUpdateStrategy): + def update_x(x): + self._update_jac() + self.x_prev = self.x + self.J_prev = self.J + _x = atleast_nd(x, ndim=1, xp=self.xp) + self.x = self.xp.astype(_x, self.x_dtype) + self.f_updated = False + self.J_updated = False + self.H_updated = False + self._update_hess() + else: + def update_x(x): + _x = atleast_nd(x, ndim=1, xp=self.xp) + self.x = self.xp.astype(_x, self.x_dtype) + self.f_updated = False + self.J_updated = False + self.H_updated = False + + self._update_x_impl = update_x + + def _update_v(self, v): + if not np.array_equal(v, self.v): + self.v = v + self.H_updated = False + + def _update_x(self, x): + if not np.array_equal(x, self.x): + self._update_x_impl(x) + + def _update_fun(self): + if not self.f_updated: + self._update_fun_impl() + self.f_updated = True + + def _update_jac(self): + if not self.J_updated: + self._update_jac_impl() + self.J_updated = True + + def _update_hess(self): + if not self.H_updated: + self._update_hess_impl() + self.H_updated = True + + def fun(self, x): + self._update_x(x) + self._update_fun() + return self.f + + def jac(self, x): + self._update_x(x) + self._update_jac() + return self.J + + def hess(self, x, v): + # v should be updated before x. + self._update_v(v) + self._update_x(x) + self._update_hess() + return self.H + + +class LinearVectorFunction: + """Linear vector function and its derivatives. + + Defines a linear function F = A x, where x is N-D vector and + A is m-by-n matrix. The Jacobian is constant and equals to A. The Hessian + is identically zero and it is returned as a csr matrix. + """ + def __init__(self, A, x0, sparse_jacobian): + if sparse_jacobian or sparse_jacobian is None and sps.issparse(A): + self.J = sps.csr_matrix(A) + self.sparse_jacobian = True + elif sps.issparse(A): + self.J = A.toarray() + self.sparse_jacobian = False + else: + # np.asarray makes sure A is ndarray and not matrix + self.J = np.atleast_2d(np.asarray(A)) + self.sparse_jacobian = False + + self.m, self.n = self.J.shape + + self.xp = xp = array_namespace(x0) + _x = atleast_nd(x0, ndim=1, xp=xp) + _dtype = xp.float64 + if xp.isdtype(_x.dtype, "real floating"): + _dtype = _x.dtype + + # promotes to floating + self.x = xp.astype(_x, _dtype) + self.x_dtype = _dtype + + self.f = self.J.dot(self.x) + self.f_updated = True + + self.v = np.zeros(self.m, dtype=float) + self.H = sps.csr_matrix((self.n, self.n)) + + def _update_x(self, x): + if not np.array_equal(x, self.x): + _x = atleast_nd(x, ndim=1, xp=self.xp) + self.x = self.xp.astype(_x, self.x_dtype) + self.f_updated = False + + def fun(self, x): + self._update_x(x) + if not self.f_updated: + self.f = self.J.dot(x) + self.f_updated = True + return self.f + + def jac(self, x): + self._update_x(x) + return self.J + + def hess(self, x, v): + self._update_x(x) + self.v = v + return self.H + + +class IdentityVectorFunction(LinearVectorFunction): + """Identity vector function and its derivatives. + + The Jacobian is the identity matrix, returned as a dense array when + `sparse_jacobian=False` and as a csr matrix otherwise. The Hessian is + identically zero and it is returned as a csr matrix. + """ + def __init__(self, x0, sparse_jacobian): + n = len(x0) + if sparse_jacobian or sparse_jacobian is None: + A = sps.eye(n, format='csr') + sparse_jacobian = True + else: + A = np.eye(n) + sparse_jacobian = False + super().__init__(A, x0, sparse_jacobian) diff --git a/llava_next/lib/python3.10/site-packages/scipy/optimize/_differentialevolution.py b/llava_next/lib/python3.10/site-packages/scipy/optimize/_differentialevolution.py new file mode 100644 index 0000000000000000000000000000000000000000..815d27afd072cd7a114dbc8bb9447ffbc09285f4 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/scipy/optimize/_differentialevolution.py @@ -0,0 +1,1951 @@ +""" +differential_evolution: The differential evolution global optimization algorithm +Added by Andrew Nelson 2014 +""" +import warnings + +import numpy as np +from scipy.optimize import OptimizeResult, minimize +from scipy.optimize._optimize import _status_message, _wrap_callback +from scipy._lib._util import (check_random_state, MapWrapper, _FunctionWrapper, + rng_integers) + +from scipy.optimize._constraints import (Bounds, new_bounds_to_old, + NonlinearConstraint, LinearConstraint) +from scipy.sparse import issparse + +__all__ = ['differential_evolution'] + + +_MACHEPS = np.finfo(np.float64).eps + + +def differential_evolution(func, bounds, args=(), strategy='best1bin', + maxiter=1000, popsize=15, tol=0.01, + mutation=(0.5, 1), recombination=0.7, seed=None, + callback=None, disp=False, polish=True, + init='latinhypercube', atol=0, updating='immediate', + workers=1, constraints=(), x0=None, *, + integrality=None, vectorized=False): + """Finds the global minimum of a multivariate function. + + The differential evolution method [1]_ is stochastic in nature. It does + not use gradient methods to find the minimum, and can search large areas + of candidate space, but often requires larger numbers of function + evaluations than conventional gradient-based techniques. + + The algorithm is due to Storn and Price [2]_. + + Parameters + ---------- + func : callable + The objective function to be minimized. Must be in the form + ``f(x, *args)``, where ``x`` is the argument in the form of a 1-D array + and ``args`` is a tuple of any additional fixed parameters needed to + completely specify the function. The number of parameters, N, is equal + to ``len(x)``. + bounds : sequence or `Bounds` + Bounds for variables. There are two ways to specify the bounds: + + 1. Instance of `Bounds` class. + 2. ``(min, max)`` pairs for each element in ``x``, defining the + finite lower and upper bounds for the optimizing argument of + `func`. + + The total number of bounds is used to determine the number of + parameters, N. If there are parameters whose bounds are equal the total + number of free parameters is ``N - N_equal``. + + args : tuple, optional + Any additional fixed parameters needed to + completely specify the objective function. + strategy : {str, callable}, optional + The differential evolution strategy to use. Should be one of: + + - 'best1bin' + - 'best1exp' + - 'rand1bin' + - 'rand1exp' + - 'rand2bin' + - 'rand2exp' + - 'randtobest1bin' + - 'randtobest1exp' + - 'currenttobest1bin' + - 'currenttobest1exp' + - 'best2exp' + - 'best2bin' + + The default is 'best1bin'. Strategies that may be implemented are + outlined in 'Notes'. + Alternatively the differential evolution strategy can be customized by + providing a callable that constructs a trial vector. The callable must + have the form ``strategy(candidate: int, population: np.ndarray, rng=None)``, + where ``candidate`` is an integer specifying which entry of the + population is being evolved, ``population`` is an array of shape + ``(S, N)`` containing all the population members (where S is the + total population size), and ``rng`` is the random number generator + being used within the solver. + ``candidate`` will be in the range ``[0, S)``. + ``strategy`` must return a trial vector with shape `(N,)`. The + fitness of this trial vector is compared against the fitness of + ``population[candidate]``. + + .. versionchanged:: 1.12.0 + Customization of evolution strategy via a callable. + + maxiter : int, optional + The maximum number of generations over which the entire population is + evolved. The maximum number of function evaluations (with no polishing) + is: ``(maxiter + 1) * popsize * (N - N_equal)`` + popsize : int, optional + A multiplier for setting the total population size. The population has + ``popsize * (N - N_equal)`` individuals. This keyword is overridden if + an initial population is supplied via the `init` keyword. When using + ``init='sobol'`` the population size is calculated as the next power + of 2 after ``popsize * (N - N_equal)``. + tol : float, optional + Relative tolerance for convergence, the solving stops when + ``np.std(pop) <= atol + tol * np.abs(np.mean(population_energies))``, + where and `atol` and `tol` are the absolute and relative tolerance + respectively. + mutation : float or tuple(float, float), optional + The mutation constant. In the literature this is also known as + differential weight, being denoted by F. + If specified as a float it should be in the range [0, 2]. + If specified as a tuple ``(min, max)`` dithering is employed. Dithering + randomly changes the mutation constant on a generation by generation + basis. The mutation constant for that generation is taken from + ``U[min, max)``. Dithering can help speed convergence significantly. + Increasing the mutation constant increases the search radius, but will + slow down convergence. + recombination : float, optional + The recombination constant, should be in the range [0, 1]. In the + literature this is also known as the crossover probability, being + denoted by CR. Increasing this value allows a larger number of mutants + to progress into the next generation, but at the risk of population + stability. + seed : {None, int, `numpy.random.Generator`, `numpy.random.RandomState`}, optional + If `seed` is None (or `np.random`), the `numpy.random.RandomState` + singleton is used. + If `seed` is an int, a new ``RandomState`` instance is used, + seeded with `seed`. + If `seed` is already a ``Generator`` or ``RandomState`` instance then + that instance is used. + Specify `seed` for repeatable minimizations. + disp : bool, optional + Prints the evaluated `func` at every iteration. + callback : callable, optional + A callable called after each iteration. Has the signature: + + ``callback(intermediate_result: OptimizeResult)`` + + where ``intermediate_result`` is a keyword parameter containing an + `OptimizeResult` with attributes ``x`` and ``fun``, the best solution + found so far and the objective function. Note that the name + of the parameter must be ``intermediate_result`` for the callback + to be passed an `OptimizeResult`. + + The callback also supports a signature like: + + ``callback(x, convergence: float=val)`` + + ``val`` represents the fractional value of the population convergence. + When ``val`` is greater than ``1.0``, the function halts. + + Introspection is used to determine which of the signatures is invoked. + + Global minimization will halt if the callback raises ``StopIteration`` + or returns ``True``; any polishing is still carried out. + + .. versionchanged:: 1.12.0 + callback accepts the ``intermediate_result`` keyword. + + polish : bool, optional + If True (default), then `scipy.optimize.minimize` with the `L-BFGS-B` + method is used to polish the best population member at the end, which + can improve the minimization slightly. If a constrained problem is + being studied then the `trust-constr` method is used instead. For large + problems with many constraints, polishing can take a long time due to + the Jacobian computations. + init : str or array-like, optional + Specify which type of population initialization is performed. Should be + one of: + + - 'latinhypercube' + - 'sobol' + - 'halton' + - 'random' + - array specifying the initial population. The array should have + shape ``(S, N)``, where S is the total population size and N is + the number of parameters. + `init` is clipped to `bounds` before use. + + The default is 'latinhypercube'. Latin Hypercube sampling tries to + maximize coverage of the available parameter space. + + 'sobol' and 'halton' are superior alternatives and maximize even more + the parameter space. 'sobol' will enforce an initial population + size which is calculated as the next power of 2 after + ``popsize * (N - N_equal)``. 'halton' has no requirements but is a bit + less efficient. See `scipy.stats.qmc` for more details. + + 'random' initializes the population randomly - this has the drawback + that clustering can occur, preventing the whole of parameter space + being covered. Use of an array to specify a population could be used, + for example, to create a tight bunch of initial guesses in an location + where the solution is known to exist, thereby reducing time for + convergence. + atol : float, optional + Absolute tolerance for convergence, the solving stops when + ``np.std(pop) <= atol + tol * np.abs(np.mean(population_energies))``, + where and `atol` and `tol` are the absolute and relative tolerance + respectively. + updating : {'immediate', 'deferred'}, optional + If ``'immediate'``, the best solution vector is continuously updated + within a single generation [4]_. This can lead to faster convergence as + trial vectors can take advantage of continuous improvements in the best + solution. + With ``'deferred'``, the best solution vector is updated once per + generation. Only ``'deferred'`` is compatible with parallelization or + vectorization, and the `workers` and `vectorized` keywords can + over-ride this option. + + .. versionadded:: 1.2.0 + + workers : int or map-like callable, optional + If `workers` is an int the population is subdivided into `workers` + sections and evaluated in parallel + (uses `multiprocessing.Pool `). + Supply -1 to use all available CPU cores. + Alternatively supply a map-like callable, such as + `multiprocessing.Pool.map` for evaluating the population in parallel. + This evaluation is carried out as ``workers(func, iterable)``. + This option will override the `updating` keyword to + ``updating='deferred'`` if ``workers != 1``. + This option overrides the `vectorized` keyword if ``workers != 1``. + Requires that `func` be pickleable. + + .. versionadded:: 1.2.0 + + constraints : {NonLinearConstraint, LinearConstraint, Bounds} + Constraints on the solver, over and above those applied by the `bounds` + kwd. Uses the approach by Lampinen [5]_. + + .. versionadded:: 1.4.0 + + x0 : None or array-like, optional + Provides an initial guess to the minimization. Once the population has + been initialized this vector replaces the first (best) member. This + replacement is done even if `init` is given an initial population. + ``x0.shape == (N,)``. + + .. versionadded:: 1.7.0 + + integrality : 1-D array, optional + For each decision variable, a boolean value indicating whether the + decision variable is constrained to integer values. The array is + broadcast to ``(N,)``. + If any decision variables are constrained to be integral, they will not + be changed during polishing. + Only integer values lying between the lower and upper bounds are used. + If there are no integer values lying between the bounds then a + `ValueError` is raised. + + .. versionadded:: 1.9.0 + + vectorized : bool, optional + If ``vectorized is True``, `func` is sent an `x` array with + ``x.shape == (N, S)``, and is expected to return an array of shape + ``(S,)``, where `S` is the number of solution vectors to be calculated. + If constraints are applied, each of the functions used to construct + a `Constraint` object should accept an `x` array with + ``x.shape == (N, S)``, and return an array of shape ``(M, S)``, where + `M` is the number of constraint components. + This option is an alternative to the parallelization offered by + `workers`, and may help in optimization speed by reducing interpreter + overhead from multiple function calls. This keyword is ignored if + ``workers != 1``. + This option will override the `updating` keyword to + ``updating='deferred'``. + See the notes section for further discussion on when to use + ``'vectorized'``, and when to use ``'workers'``. + + .. versionadded:: 1.9.0 + + Returns + ------- + res : OptimizeResult + The optimization result represented as a `OptimizeResult` object. + Important attributes are: ``x`` the solution array, ``success`` a + Boolean flag indicating if the optimizer exited successfully, + ``message`` which describes the cause of the termination, + ``population`` the solution vectors present in the population, and + ``population_energies`` the value of the objective function for each + entry in ``population``. + See `OptimizeResult` for a description of other attributes. If `polish` + was employed, and a lower minimum was obtained by the polishing, then + OptimizeResult also contains the ``jac`` attribute. + If the eventual solution does not satisfy the applied constraints + ``success`` will be `False`. + + Notes + ----- + Differential evolution is a stochastic population based method that is + useful for global optimization problems. At each pass through the + population the algorithm mutates each candidate solution by mixing with + other candidate solutions to create a trial candidate. There are several + strategies [3]_ for creating trial candidates, which suit some problems + more than others. The 'best1bin' strategy is a good starting point for + many systems. In this strategy two members of the population are randomly + chosen. Their difference is used to mutate the best member (the 'best' in + 'best1bin'), :math:`x_0`, so far: + + .. math:: + + b' = x_0 + mutation * (x_{r_0} - x_{r_1}) + + A trial vector is then constructed. Starting with a randomly chosen ith + parameter the trial is sequentially filled (in modulo) with parameters + from ``b'`` or the original candidate. The choice of whether to use ``b'`` + or the original candidate is made with a binomial distribution (the 'bin' + in 'best1bin') - a random number in [0, 1) is generated. If this number is + less than the `recombination` constant then the parameter is loaded from + ``b'``, otherwise it is loaded from the original candidate. The final + parameter is always loaded from ``b'``. Once the trial candidate is built + its fitness is assessed. If the trial is better than the original candidate + then it takes its place. If it is also better than the best overall + candidate it also replaces that. + + The other strategies available are outlined in Qiang and + Mitchell (2014) [3]_. + + .. math:: + rand1* : b' = x_{r_0} + mutation*(x_{r_1} - x_{r_2}) + + rand2* : b' = x_{r_0} + mutation*(x_{r_1} + x_{r_2} + - x_{r_3} - x_{r_4}) + + best1* : b' = x_0 + mutation*(x_{r_0} - x_{r_1}) + + best2* : b' = x_0 + mutation*(x_{r_0} + x_{r_1} + - x_{r_2} - x_{r_3}) + + currenttobest1* : b' = x_i + mutation*(x_0 - x_i + + x_{r_0} - x_{r_1}) + + randtobest1* : b' = x_{r_0} + mutation*(x_0 - x_{r_0} + + x_{r_1} - x_{r_2}) + + where the integers :math:`r_0, r_1, r_2, r_3, r_4` are chosen randomly + from the interval [0, NP) with `NP` being the total population size and + the original candidate having index `i`. The user can fully customize the + generation of the trial candidates by supplying a callable to ``strategy``. + + To improve your chances of finding a global minimum use higher `popsize` + values, with higher `mutation` and (dithering), but lower `recombination` + values. This has the effect of widening the search radius, but slowing + convergence. + + By default the best solution vector is updated continuously within a single + iteration (``updating='immediate'``). This is a modification [4]_ of the + original differential evolution algorithm which can lead to faster + convergence as trial vectors can immediately benefit from improved + solutions. To use the original Storn and Price behaviour, updating the best + solution once per iteration, set ``updating='deferred'``. + The ``'deferred'`` approach is compatible with both parallelization and + vectorization (``'workers'`` and ``'vectorized'`` keywords). These may + improve minimization speed by using computer resources more efficiently. + The ``'workers'`` distribute calculations over multiple processors. By + default the Python `multiprocessing` module is used, but other approaches + are also possible, such as the Message Passing Interface (MPI) used on + clusters [6]_ [7]_. The overhead from these approaches (creating new + Processes, etc) may be significant, meaning that computational speed + doesn't necessarily scale with the number of processors used. + Parallelization is best suited to computationally expensive objective + functions. If the objective function is less expensive, then + ``'vectorized'`` may aid by only calling the objective function once per + iteration, rather than multiple times for all the population members; the + interpreter overhead is reduced. + + .. versionadded:: 0.15.0 + + References + ---------- + .. [1] Differential evolution, Wikipedia, + http://en.wikipedia.org/wiki/Differential_evolution + .. [2] Storn, R and Price, K, Differential Evolution - a Simple and + Efficient Heuristic for Global Optimization over Continuous Spaces, + Journal of Global Optimization, 1997, 11, 341 - 359. + .. [3] Qiang, J., Mitchell, C., A Unified Differential Evolution Algorithm + for Global Optimization, 2014, https://www.osti.gov/servlets/purl/1163659 + .. [4] Wormington, M., Panaccione, C., Matney, K. M., Bowen, D. K., - + Characterization of structures from X-ray scattering data using + genetic algorithms, Phil. Trans. R. Soc. Lond. A, 1999, 357, + 2827-2848 + .. [5] Lampinen, J., A constraint handling approach for the differential + evolution algorithm. Proceedings of the 2002 Congress on + Evolutionary Computation. CEC'02 (Cat. No. 02TH8600). Vol. 2. IEEE, + 2002. + .. [6] https://mpi4py.readthedocs.io/en/stable/ + .. [7] https://schwimmbad.readthedocs.io/en/latest/ + + + Examples + -------- + Let us consider the problem of minimizing the Rosenbrock function. This + function is implemented in `rosen` in `scipy.optimize`. + + >>> import numpy as np + >>> from scipy.optimize import rosen, differential_evolution + >>> bounds = [(0,2), (0, 2), (0, 2), (0, 2), (0, 2)] + >>> result = differential_evolution(rosen, bounds) + >>> result.x, result.fun + (array([1., 1., 1., 1., 1.]), 1.9216496320061384e-19) + + Now repeat, but with parallelization. + + >>> result = differential_evolution(rosen, bounds, updating='deferred', + ... workers=2) + >>> result.x, result.fun + (array([1., 1., 1., 1., 1.]), 1.9216496320061384e-19) + + Let's do a constrained minimization. + + >>> from scipy.optimize import LinearConstraint, Bounds + + We add the constraint that the sum of ``x[0]`` and ``x[1]`` must be less + than or equal to 1.9. This is a linear constraint, which may be written + ``A @ x <= 1.9``, where ``A = array([[1, 1]])``. This can be encoded as + a `LinearConstraint` instance: + + >>> lc = LinearConstraint([[1, 1]], -np.inf, 1.9) + + Specify limits using a `Bounds` object. + + >>> bounds = Bounds([0., 0.], [2., 2.]) + >>> result = differential_evolution(rosen, bounds, constraints=lc, + ... seed=1) + >>> result.x, result.fun + (array([0.96632622, 0.93367155]), 0.0011352416852625719) + + Next find the minimum of the Ackley function + (https://en.wikipedia.org/wiki/Test_functions_for_optimization). + + >>> def ackley(x): + ... arg1 = -0.2 * np.sqrt(0.5 * (x[0] ** 2 + x[1] ** 2)) + ... arg2 = 0.5 * (np.cos(2. * np.pi * x[0]) + np.cos(2. * np.pi * x[1])) + ... return -20. * np.exp(arg1) - np.exp(arg2) + 20. + np.e + >>> bounds = [(-5, 5), (-5, 5)] + >>> result = differential_evolution(ackley, bounds, seed=1) + >>> result.x, result.fun + (array([0., 0.]), 4.440892098500626e-16) + + The Ackley function is written in a vectorized manner, so the + ``'vectorized'`` keyword can be employed. Note the reduced number of + function evaluations. + + >>> result = differential_evolution( + ... ackley, bounds, vectorized=True, updating='deferred', seed=1 + ... ) + >>> result.x, result.fun + (array([0., 0.]), 4.440892098500626e-16) + + The following custom strategy function mimics 'best1bin': + + >>> def custom_strategy_fn(candidate, population, rng=None): + ... parameter_count = population.shape(-1) + ... mutation, recombination = 0.7, 0.9 + ... trial = np.copy(population[candidate]) + ... fill_point = rng.choice(parameter_count) + ... + ... pool = np.arange(len(population)) + ... rng.shuffle(pool) + ... + ... # two unique random numbers that aren't the same, and + ... # aren't equal to candidate. + ... idxs = [] + ... while len(idxs) < 2 and len(pool) > 0: + ... idx = pool[0] + ... pool = pool[1:] + ... if idx != candidate: + ... idxs.append(idx) + ... + ... r0, r1 = idxs[:2] + ... + ... bprime = (population[0] + mutation * + ... (population[r0] - population[r1])) + ... + ... crossovers = rng.uniform(size=parameter_count) + ... crossovers = crossovers < recombination + ... crossovers[fill_point] = True + ... trial = np.where(crossovers, bprime, trial) + ... return trial + + """ + + # using a context manager means that any created Pool objects are + # cleared up. + with DifferentialEvolutionSolver(func, bounds, args=args, + strategy=strategy, + maxiter=maxiter, + popsize=popsize, tol=tol, + mutation=mutation, + recombination=recombination, + seed=seed, polish=polish, + callback=callback, + disp=disp, init=init, atol=atol, + updating=updating, + workers=workers, + constraints=constraints, + x0=x0, + integrality=integrality, + vectorized=vectorized) as solver: + ret = solver.solve() + + return ret + + +class DifferentialEvolutionSolver: + + """This class implements the differential evolution solver + + Parameters + ---------- + func : callable + The objective function to be minimized. Must be in the form + ``f(x, *args)``, where ``x`` is the argument in the form of a 1-D array + and ``args`` is a tuple of any additional fixed parameters needed to + completely specify the function. The number of parameters, N, is equal + to ``len(x)``. + bounds : sequence or `Bounds` + Bounds for variables. There are two ways to specify the bounds: + + 1. Instance of `Bounds` class. + 2. ``(min, max)`` pairs for each element in ``x``, defining the + finite lower and upper bounds for the optimizing argument of + `func`. + + The total number of bounds is used to determine the number of + parameters, N. If there are parameters whose bounds are equal the total + number of free parameters is ``N - N_equal``. + args : tuple, optional + Any additional fixed parameters needed to + completely specify the objective function. + strategy : {str, callable}, optional + The differential evolution strategy to use. Should be one of: + + - 'best1bin' + - 'best1exp' + - 'rand1bin' + - 'rand1exp' + - 'rand2bin' + - 'rand2exp' + - 'randtobest1bin' + - 'randtobest1exp' + - 'currenttobest1bin' + - 'currenttobest1exp' + - 'best2exp' + - 'best2bin' + + The default is 'best1bin'. Strategies that may be + implemented are outlined in 'Notes'. + + Alternatively the differential evolution strategy can be customized + by providing a callable that constructs a trial vector. The callable + must have the form + ``strategy(candidate: int, population: np.ndarray, rng=None)``, + where ``candidate`` is an integer specifying which entry of the + population is being evolved, ``population`` is an array of shape + ``(S, N)`` containing all the population members (where S is the + total population size), and ``rng`` is the random number generator + being used within the solver. + ``candidate`` will be in the range ``[0, S)``. + ``strategy`` must return a trial vector with shape `(N,)`. The + fitness of this trial vector is compared against the fitness of + ``population[candidate]``. + maxiter : int, optional + The maximum number of generations over which the entire population is + evolved. The maximum number of function evaluations (with no polishing) + is: ``(maxiter + 1) * popsize * (N - N_equal)`` + popsize : int, optional + A multiplier for setting the total population size. The population has + ``popsize * (N - N_equal)`` individuals. This keyword is overridden if + an initial population is supplied via the `init` keyword. When using + ``init='sobol'`` the population size is calculated as the next power + of 2 after ``popsize * (N - N_equal)``. + tol : float, optional + Relative tolerance for convergence, the solving stops when + ``np.std(pop) <= atol + tol * np.abs(np.mean(population_energies))``, + where and `atol` and `tol` are the absolute and relative tolerance + respectively. + mutation : float or tuple(float, float), optional + The mutation constant. In the literature this is also known as + differential weight, being denoted by F. + If specified as a float it should be in the range [0, 2]. + If specified as a tuple ``(min, max)`` dithering is employed. Dithering + randomly changes the mutation constant on a generation by generation + basis. The mutation constant for that generation is taken from + U[min, max). Dithering can help speed convergence significantly. + Increasing the mutation constant increases the search radius, but will + slow down convergence. + recombination : float, optional + The recombination constant, should be in the range [0, 1]. In the + literature this is also known as the crossover probability, being + denoted by CR. Increasing this value allows a larger number of mutants + to progress into the next generation, but at the risk of population + stability. + seed : {None, int, `numpy.random.Generator`, `numpy.random.RandomState`}, optional + If `seed` is None (or `np.random`), the `numpy.random.RandomState` + singleton is used. + If `seed` is an int, a new ``RandomState`` instance is used, + seeded with `seed`. + If `seed` is already a ``Generator`` or ``RandomState`` instance then + that instance is used. + Specify `seed` for repeatable minimizations. + disp : bool, optional + Prints the evaluated `func` at every iteration. + callback : callable, optional + A callable called after each iteration. Has the signature: + + ``callback(intermediate_result: OptimizeResult)`` + + where ``intermediate_result`` is a keyword parameter containing an + `OptimizeResult` with attributes ``x`` and ``fun``, the best solution + found so far and the objective function. Note that the name + of the parameter must be ``intermediate_result`` for the callback + to be passed an `OptimizeResult`. + + The callback also supports a signature like: + + ``callback(x, convergence: float=val)`` + + ``val`` represents the fractional value of the population convergence. + When ``val`` is greater than ``1.0``, the function halts. + + Introspection is used to determine which of the signatures is invoked. + + Global minimization will halt if the callback raises ``StopIteration`` + or returns ``True``; any polishing is still carried out. + + .. versionchanged:: 1.12.0 + callback accepts the ``intermediate_result`` keyword. + + polish : bool, optional + If True (default), then `scipy.optimize.minimize` with the `L-BFGS-B` + method is used to polish the best population member at the end, which + can improve the minimization slightly. If a constrained problem is + being studied then the `trust-constr` method is used instead. For large + problems with many constraints, polishing can take a long time due to + the Jacobian computations. + maxfun : int, optional + Set the maximum number of function evaluations. However, it probably + makes more sense to set `maxiter` instead. + init : str or array-like, optional + Specify which type of population initialization is performed. Should be + one of: + + - 'latinhypercube' + - 'sobol' + - 'halton' + - 'random' + - array specifying the initial population. The array should have + shape ``(S, N)``, where S is the total population size and + N is the number of parameters. + `init` is clipped to `bounds` before use. + + The default is 'latinhypercube'. Latin Hypercube sampling tries to + maximize coverage of the available parameter space. + + 'sobol' and 'halton' are superior alternatives and maximize even more + the parameter space. 'sobol' will enforce an initial population + size which is calculated as the next power of 2 after + ``popsize * (N - N_equal)``. 'halton' has no requirements but is a bit + less efficient. See `scipy.stats.qmc` for more details. + + 'random' initializes the population randomly - this has the drawback + that clustering can occur, preventing the whole of parameter space + being covered. Use of an array to specify a population could be used, + for example, to create a tight bunch of initial guesses in an location + where the solution is known to exist, thereby reducing time for + convergence. + atol : float, optional + Absolute tolerance for convergence, the solving stops when + ``np.std(pop) <= atol + tol * np.abs(np.mean(population_energies))``, + where and `atol` and `tol` are the absolute and relative tolerance + respectively. + updating : {'immediate', 'deferred'}, optional + If ``'immediate'``, the best solution vector is continuously updated + within a single generation [4]_. This can lead to faster convergence as + trial vectors can take advantage of continuous improvements in the best + solution. + With ``'deferred'``, the best solution vector is updated once per + generation. Only ``'deferred'`` is compatible with parallelization or + vectorization, and the `workers` and `vectorized` keywords can + over-ride this option. + workers : int or map-like callable, optional + If `workers` is an int the population is subdivided into `workers` + sections and evaluated in parallel + (uses `multiprocessing.Pool `). + Supply `-1` to use all cores available to the Process. + Alternatively supply a map-like callable, such as + `multiprocessing.Pool.map` for evaluating the population in parallel. + This evaluation is carried out as ``workers(func, iterable)``. + This option will override the `updating` keyword to + `updating='deferred'` if `workers != 1`. + Requires that `func` be pickleable. + constraints : {NonLinearConstraint, LinearConstraint, Bounds} + Constraints on the solver, over and above those applied by the `bounds` + kwd. Uses the approach by Lampinen. + x0 : None or array-like, optional + Provides an initial guess to the minimization. Once the population has + been initialized this vector replaces the first (best) member. This + replacement is done even if `init` is given an initial population. + ``x0.shape == (N,)``. + integrality : 1-D array, optional + For each decision variable, a boolean value indicating whether the + decision variable is constrained to integer values. The array is + broadcast to ``(N,)``. + If any decision variables are constrained to be integral, they will not + be changed during polishing. + Only integer values lying between the lower and upper bounds are used. + If there are no integer values lying between the bounds then a + `ValueError` is raised. + vectorized : bool, optional + If ``vectorized is True``, `func` is sent an `x` array with + ``x.shape == (N, S)``, and is expected to return an array of shape + ``(S,)``, where `S` is the number of solution vectors to be calculated. + If constraints are applied, each of the functions used to construct + a `Constraint` object should accept an `x` array with + ``x.shape == (N, S)``, and return an array of shape ``(M, S)``, where + `M` is the number of constraint components. + This option is an alternative to the parallelization offered by + `workers`, and may help in optimization speed. This keyword is + ignored if ``workers != 1``. + This option will override the `updating` keyword to + ``updating='deferred'``. + """ + + # Dispatch of mutation strategy method (binomial or exponential). + _binomial = {'best1bin': '_best1', + 'randtobest1bin': '_randtobest1', + 'currenttobest1bin': '_currenttobest1', + 'best2bin': '_best2', + 'rand2bin': '_rand2', + 'rand1bin': '_rand1'} + _exponential = {'best1exp': '_best1', + 'rand1exp': '_rand1', + 'randtobest1exp': '_randtobest1', + 'currenttobest1exp': '_currenttobest1', + 'best2exp': '_best2', + 'rand2exp': '_rand2'} + + __init_error_msg = ("The population initialization method must be one of " + "'latinhypercube' or 'random', or an array of shape " + "(S, N) where N is the number of parameters and S>5") + + def __init__(self, func, bounds, args=(), + strategy='best1bin', maxiter=1000, popsize=15, + tol=0.01, mutation=(0.5, 1), recombination=0.7, seed=None, + maxfun=np.inf, callback=None, disp=False, polish=True, + init='latinhypercube', atol=0, updating='immediate', + workers=1, constraints=(), x0=None, *, integrality=None, + vectorized=False): + + if callable(strategy): + # a callable strategy is going to be stored in self.strategy anyway + pass + elif strategy in self._binomial: + self.mutation_func = getattr(self, self._binomial[strategy]) + elif strategy in self._exponential: + self.mutation_func = getattr(self, self._exponential[strategy]) + else: + raise ValueError("Please select a valid mutation strategy") + self.strategy = strategy + + self.callback = _wrap_callback(callback, "differential_evolution") + self.polish = polish + + # set the updating / parallelisation options + if updating in ['immediate', 'deferred']: + self._updating = updating + + self.vectorized = vectorized + + # want to use parallelisation, but updating is immediate + if workers != 1 and updating == 'immediate': + warnings.warn("differential_evolution: the 'workers' keyword has" + " overridden updating='immediate' to" + " updating='deferred'", UserWarning, stacklevel=2) + self._updating = 'deferred' + + if vectorized and workers != 1: + warnings.warn("differential_evolution: the 'workers' keyword" + " overrides the 'vectorized' keyword", stacklevel=2) + self.vectorized = vectorized = False + + if vectorized and updating == 'immediate': + warnings.warn("differential_evolution: the 'vectorized' keyword" + " has overridden updating='immediate' to updating" + "='deferred'", UserWarning, stacklevel=2) + self._updating = 'deferred' + + # an object with a map method. + if vectorized: + def maplike_for_vectorized_func(func, x): + # send an array (N, S) to the user func, + # expect to receive (S,). Transposition is required because + # internally the population is held as (S, N) + return np.atleast_1d(func(x.T)) + workers = maplike_for_vectorized_func + + self._mapwrapper = MapWrapper(workers) + + # relative and absolute tolerances for convergence + self.tol, self.atol = tol, atol + + # Mutation constant should be in [0, 2). If specified as a sequence + # then dithering is performed. + self.scale = mutation + if (not np.all(np.isfinite(mutation)) or + np.any(np.array(mutation) >= 2) or + np.any(np.array(mutation) < 0)): + raise ValueError('The mutation constant must be a float in ' + 'U[0, 2), or specified as a tuple(min, max)' + ' where min < max and min, max are in U[0, 2).') + + self.dither = None + if hasattr(mutation, '__iter__') and len(mutation) > 1: + self.dither = [mutation[0], mutation[1]] + self.dither.sort() + + self.cross_over_probability = recombination + + # we create a wrapped function to allow the use of map (and Pool.map + # in the future) + self.func = _FunctionWrapper(func, args) + self.args = args + + # convert tuple of lower and upper bounds to limits + # [(low_0, high_0), ..., (low_n, high_n] + # -> [[low_0, ..., low_n], [high_0, ..., high_n]] + if isinstance(bounds, Bounds): + self.limits = np.array(new_bounds_to_old(bounds.lb, + bounds.ub, + len(bounds.lb)), + dtype=float).T + else: + self.limits = np.array(bounds, dtype='float').T + + if (np.size(self.limits, 0) != 2 or not + np.all(np.isfinite(self.limits))): + raise ValueError('bounds should be a sequence containing finite ' + 'real valued (min, max) pairs for each value' + ' in x') + + if maxiter is None: # the default used to be None + maxiter = 1000 + self.maxiter = maxiter + if maxfun is None: # the default used to be None + maxfun = np.inf + self.maxfun = maxfun + + # population is scaled to between [0, 1]. + # We have to scale between parameter <-> population + # save these arguments for _scale_parameter and + # _unscale_parameter. This is an optimization + self.__scale_arg1 = 0.5 * (self.limits[0] + self.limits[1]) + self.__scale_arg2 = np.fabs(self.limits[0] - self.limits[1]) + with np.errstate(divide='ignore'): + # if lb == ub then the following line will be 1/0, which is why + # we ignore the divide by zero warning. The result from 1/0 is + # inf, so replace those values by 0. + self.__recip_scale_arg2 = 1 / self.__scale_arg2 + self.__recip_scale_arg2[~np.isfinite(self.__recip_scale_arg2)] = 0 + + self.parameter_count = np.size(self.limits, 1) + + self.random_number_generator = check_random_state(seed) + + # Which parameters are going to be integers? + if np.any(integrality): + # # user has provided a truth value for integer constraints + integrality = np.broadcast_to( + integrality, + self.parameter_count + ) + integrality = np.asarray(integrality, bool) + # For integrality parameters change the limits to only allow + # integer values lying between the limits. + lb, ub = np.copy(self.limits) + + lb = np.ceil(lb) + ub = np.floor(ub) + if not (lb[integrality] <= ub[integrality]).all(): + # there's a parameter that doesn't have an integer value + # lying between the limits + raise ValueError("One of the integrality constraints does not" + " have any possible integer values between" + " the lower/upper bounds.") + nlb = np.nextafter(lb[integrality] - 0.5, np.inf) + nub = np.nextafter(ub[integrality] + 0.5, -np.inf) + + self.integrality = integrality + self.limits[0, self.integrality] = nlb + self.limits[1, self.integrality] = nub + else: + self.integrality = False + + # check for equal bounds + eb = self.limits[0] == self.limits[1] + eb_count = np.count_nonzero(eb) + + # default population initialization is a latin hypercube design, but + # there are other population initializations possible. + # the minimum is 5 because 'best2bin' requires a population that's at + # least 5 long + # 202301 - reduced population size to account for parameters with + # equal bounds. If there are no varying parameters set N to at least 1 + self.num_population_members = max( + 5, + popsize * max(1, self.parameter_count - eb_count) + ) + self.population_shape = (self.num_population_members, + self.parameter_count) + + self._nfev = 0 + # check first str otherwise will fail to compare str with array + if isinstance(init, str): + if init == 'latinhypercube': + self.init_population_lhs() + elif init == 'sobol': + # must be Ns = 2**m for Sobol' + n_s = int(2 ** np.ceil(np.log2(self.num_population_members))) + self.num_population_members = n_s + self.population_shape = (self.num_population_members, + self.parameter_count) + self.init_population_qmc(qmc_engine='sobol') + elif init == 'halton': + self.init_population_qmc(qmc_engine='halton') + elif init == 'random': + self.init_population_random() + else: + raise ValueError(self.__init_error_msg) + else: + self.init_population_array(init) + + if x0 is not None: + # scale to within unit interval and + # ensure parameters are within bounds. + x0_scaled = self._unscale_parameters(np.asarray(x0)) + if ((x0_scaled > 1.0) | (x0_scaled < 0.0)).any(): + raise ValueError( + "Some entries in x0 lay outside the specified bounds" + ) + self.population[0] = x0_scaled + + # infrastructure for constraints + self.constraints = constraints + self._wrapped_constraints = [] + + if hasattr(constraints, '__len__'): + # sequence of constraints, this will also deal with default + # keyword parameter + for c in constraints: + self._wrapped_constraints.append( + _ConstraintWrapper(c, self.x) + ) + else: + self._wrapped_constraints = [ + _ConstraintWrapper(constraints, self.x) + ] + self.total_constraints = np.sum( + [c.num_constr for c in self._wrapped_constraints] + ) + self.constraint_violation = np.zeros((self.num_population_members, 1)) + self.feasible = np.ones(self.num_population_members, bool) + + # an array to shuffle when selecting candidates. Create it here + # rather than repeatedly creating it in _select_samples. + self._random_population_index = np.arange(self.num_population_members) + self.disp = disp + + def init_population_lhs(self): + """ + Initializes the population with Latin Hypercube Sampling. + Latin Hypercube Sampling ensures that each parameter is uniformly + sampled over its range. + """ + rng = self.random_number_generator + + # Each parameter range needs to be sampled uniformly. The scaled + # parameter range ([0, 1)) needs to be split into + # `self.num_population_members` segments, each of which has the following + # size: + segsize = 1.0 / self.num_population_members + + # Within each segment we sample from a uniform random distribution. + # We need to do this sampling for each parameter. + samples = (segsize * rng.uniform(size=self.population_shape) + + # Offset each segment to cover the entire parameter range [0, 1) + + np.linspace(0., 1., self.num_population_members, + endpoint=False)[:, np.newaxis]) + + # Create an array for population of candidate solutions. + self.population = np.zeros_like(samples) + + # Initialize population of candidate solutions by permutation of the + # random samples. + for j in range(self.parameter_count): + order = rng.permutation(range(self.num_population_members)) + self.population[:, j] = samples[order, j] + + # reset population energies + self.population_energies = np.full(self.num_population_members, + np.inf) + + # reset number of function evaluations counter + self._nfev = 0 + + def init_population_qmc(self, qmc_engine): + """Initializes the population with a QMC method. + + QMC methods ensures that each parameter is uniformly + sampled over its range. + + Parameters + ---------- + qmc_engine : str + The QMC method to use for initialization. Can be one of + ``latinhypercube``, ``sobol`` or ``halton``. + + """ + from scipy.stats import qmc + + rng = self.random_number_generator + + # Create an array for population of candidate solutions. + if qmc_engine == 'latinhypercube': + sampler = qmc.LatinHypercube(d=self.parameter_count, seed=rng) + elif qmc_engine == 'sobol': + sampler = qmc.Sobol(d=self.parameter_count, seed=rng) + elif qmc_engine == 'halton': + sampler = qmc.Halton(d=self.parameter_count, seed=rng) + else: + raise ValueError(self.__init_error_msg) + + self.population = sampler.random(n=self.num_population_members) + + # reset population energies + self.population_energies = np.full(self.num_population_members, + np.inf) + + # reset number of function evaluations counter + self._nfev = 0 + + def init_population_random(self): + """ + Initializes the population at random. This type of initialization + can possess clustering, Latin Hypercube sampling is generally better. + """ + rng = self.random_number_generator + self.population = rng.uniform(size=self.population_shape) + + # reset population energies + self.population_energies = np.full(self.num_population_members, + np.inf) + + # reset number of function evaluations counter + self._nfev = 0 + + def init_population_array(self, init): + """ + Initializes the population with a user specified population. + + Parameters + ---------- + init : np.ndarray + Array specifying subset of the initial population. The array should + have shape (S, N), where N is the number of parameters. + The population is clipped to the lower and upper bounds. + """ + # make sure you're using a float array + popn = np.asarray(init, dtype=np.float64) + + if (np.size(popn, 0) < 5 or + popn.shape[1] != self.parameter_count or + len(popn.shape) != 2): + raise ValueError("The population supplied needs to have shape" + " (S, len(x)), where S > 4.") + + # scale values and clip to bounds, assigning to population + self.population = np.clip(self._unscale_parameters(popn), 0, 1) + + self.num_population_members = np.size(self.population, 0) + + self.population_shape = (self.num_population_members, + self.parameter_count) + + # reset population energies + self.population_energies = np.full(self.num_population_members, + np.inf) + + # reset number of function evaluations counter + self._nfev = 0 + + @property + def x(self): + """ + The best solution from the solver + """ + return self._scale_parameters(self.population[0]) + + @property + def convergence(self): + """ + The standard deviation of the population energies divided by their + mean. + """ + if np.any(np.isinf(self.population_energies)): + return np.inf + return (np.std(self.population_energies) / + (np.abs(np.mean(self.population_energies)) + _MACHEPS)) + + def converged(self): + """ + Return True if the solver has converged. + """ + if np.any(np.isinf(self.population_energies)): + return False + + return (np.std(self.population_energies) <= + self.atol + + self.tol * np.abs(np.mean(self.population_energies))) + + def solve(self): + """ + Runs the DifferentialEvolutionSolver. + + Returns + ------- + res : OptimizeResult + The optimization result represented as a `OptimizeResult` object. + Important attributes are: ``x`` the solution array, ``success`` a + Boolean flag indicating if the optimizer exited successfully, + ``message`` which describes the cause of the termination, + ``population`` the solution vectors present in the population, and + ``population_energies`` the value of the objective function for + each entry in ``population``. + See `OptimizeResult` for a description of other attributes. If + `polish` was employed, and a lower minimum was obtained by the + polishing, then OptimizeResult also contains the ``jac`` attribute. + If the eventual solution does not satisfy the applied constraints + ``success`` will be `False`. + """ + nit, warning_flag = 0, False + status_message = _status_message['success'] + + # The population may have just been initialized (all entries are + # np.inf). If it has you have to calculate the initial energies. + # Although this is also done in the evolve generator it's possible + # that someone can set maxiter=0, at which point we still want the + # initial energies to be calculated (the following loop isn't run). + if np.all(np.isinf(self.population_energies)): + self.feasible, self.constraint_violation = ( + self._calculate_population_feasibilities(self.population)) + + # only work out population energies for feasible solutions + self.population_energies[self.feasible] = ( + self._calculate_population_energies( + self.population[self.feasible])) + + self._promote_lowest_energy() + + # do the optimization. + for nit in range(1, self.maxiter + 1): + # evolve the population by a generation + try: + next(self) + except StopIteration: + warning_flag = True + if self._nfev > self.maxfun: + status_message = _status_message['maxfev'] + elif self._nfev == self.maxfun: + status_message = ('Maximum number of function evaluations' + ' has been reached.') + break + + if self.disp: + print(f"differential_evolution step {nit}: f(x)=" + f" {self.population_energies[0]}" + ) + + if self.callback: + c = self.tol / (self.convergence + _MACHEPS) + res = self._result(nit=nit, message="in progress") + res.convergence = c + try: + warning_flag = bool(self.callback(res)) + except StopIteration: + warning_flag = True + + if warning_flag: + status_message = 'callback function requested stop early' + + # should the solver terminate? + if warning_flag or self.converged(): + break + + else: + status_message = _status_message['maxiter'] + warning_flag = True + + DE_result = self._result( + nit=nit, message=status_message, warning_flag=warning_flag + ) + + if self.polish and not np.all(self.integrality): + # can't polish if all the parameters are integers + if np.any(self.integrality): + # set the lower/upper bounds equal so that any integrality + # constraints work. + limits, integrality = self.limits, self.integrality + limits[0, integrality] = DE_result.x[integrality] + limits[1, integrality] = DE_result.x[integrality] + + polish_method = 'L-BFGS-B' + + if self._wrapped_constraints: + polish_method = 'trust-constr' + + constr_violation = self._constraint_violation_fn(DE_result.x) + if np.any(constr_violation > 0.): + warnings.warn("differential evolution didn't find a " + "solution satisfying the constraints, " + "attempting to polish from the least " + "infeasible solution", + UserWarning, stacklevel=2) + if self.disp: + print(f"Polishing solution with '{polish_method}'") + result = minimize(self.func, + np.copy(DE_result.x), + method=polish_method, + bounds=self.limits.T, + constraints=self.constraints) + + self._nfev += result.nfev + DE_result.nfev = self._nfev + + # Polishing solution is only accepted if there is an improvement in + # cost function, the polishing was successful and the solution lies + # within the bounds. + if (result.fun < DE_result.fun and + result.success and + np.all(result.x <= self.limits[1]) and + np.all(self.limits[0] <= result.x)): + DE_result.fun = result.fun + DE_result.x = result.x + DE_result.jac = result.jac + # to keep internal state consistent + self.population_energies[0] = result.fun + self.population[0] = self._unscale_parameters(result.x) + + if self._wrapped_constraints: + DE_result.constr = [c.violation(DE_result.x) for + c in self._wrapped_constraints] + DE_result.constr_violation = np.max( + np.concatenate(DE_result.constr)) + DE_result.maxcv = DE_result.constr_violation + if DE_result.maxcv > 0: + # if the result is infeasible then success must be False + DE_result.success = False + DE_result.message = ("The solution does not satisfy the " + f"constraints, MAXCV = {DE_result.maxcv}") + + return DE_result + + def _result(self, **kwds): + # form an intermediate OptimizeResult + nit = kwds.get('nit', None) + message = kwds.get('message', None) + warning_flag = kwds.get('warning_flag', False) + result = OptimizeResult( + x=self.x, + fun=self.population_energies[0], + nfev=self._nfev, + nit=nit, + message=message, + success=(warning_flag is not True), + population=self._scale_parameters(self.population), + population_energies=self.population_energies + ) + if self._wrapped_constraints: + result.constr = [c.violation(result.x) + for c in self._wrapped_constraints] + result.constr_violation = np.max(np.concatenate(result.constr)) + result.maxcv = result.constr_violation + if result.maxcv > 0: + result.success = False + + return result + + def _calculate_population_energies(self, population): + """ + Calculate the energies of a population. + + Parameters + ---------- + population : ndarray + An array of parameter vectors normalised to [0, 1] using lower + and upper limits. Has shape ``(np.size(population, 0), N)``. + + Returns + ------- + energies : ndarray + An array of energies corresponding to each population member. If + maxfun will be exceeded during this call, then the number of + function evaluations will be reduced and energies will be + right-padded with np.inf. Has shape ``(np.size(population, 0),)`` + """ + num_members = np.size(population, 0) + # S is the number of function evals left to stay under the + # maxfun budget + S = min(num_members, self.maxfun - self._nfev) + + energies = np.full(num_members, np.inf) + + parameters_pop = self._scale_parameters(population) + try: + calc_energies = list( + self._mapwrapper(self.func, parameters_pop[0:S]) + ) + calc_energies = np.squeeze(calc_energies) + except (TypeError, ValueError) as e: + # wrong number of arguments for _mapwrapper + # or wrong length returned from the mapper + raise RuntimeError( + "The map-like callable must be of the form f(func, iterable), " + "returning a sequence of numbers the same length as 'iterable'" + ) from e + + if calc_energies.size != S: + if self.vectorized: + raise RuntimeError("The vectorized function must return an" + " array of shape (S,) when given an array" + " of shape (len(x), S)") + raise RuntimeError("func(x, *args) must return a scalar value") + + energies[0:S] = calc_energies + + if self.vectorized: + self._nfev += 1 + else: + self._nfev += S + + return energies + + def _promote_lowest_energy(self): + # swaps 'best solution' into first population entry + + idx = np.arange(self.num_population_members) + feasible_solutions = idx[self.feasible] + if feasible_solutions.size: + # find the best feasible solution + idx_t = np.argmin(self.population_energies[feasible_solutions]) + l = feasible_solutions[idx_t] + else: + # no solution was feasible, use 'best' infeasible solution, which + # will violate constraints the least + l = np.argmin(np.sum(self.constraint_violation, axis=1)) + + self.population_energies[[0, l]] = self.population_energies[[l, 0]] + self.population[[0, l], :] = self.population[[l, 0], :] + self.feasible[[0, l]] = self.feasible[[l, 0]] + self.constraint_violation[[0, l], :] = ( + self.constraint_violation[[l, 0], :]) + + def _constraint_violation_fn(self, x): + """ + Calculates total constraint violation for all the constraints, for a + set of solutions. + + Parameters + ---------- + x : ndarray + Solution vector(s). Has shape (S, N), or (N,), where S is the + number of solutions to investigate and N is the number of + parameters. + + Returns + ------- + cv : ndarray + Total violation of constraints. Has shape ``(S, M)``, where M is + the total number of constraint components (which is not necessarily + equal to len(self._wrapped_constraints)). + """ + # how many solution vectors you're calculating constraint violations + # for + S = np.size(x) // self.parameter_count + _out = np.zeros((S, self.total_constraints)) + offset = 0 + for con in self._wrapped_constraints: + # the input/output of the (vectorized) constraint function is + # {(N, S), (N,)} --> (M, S) + # The input to _constraint_violation_fn is (S, N) or (N,), so + # transpose to pass it to the constraint. The output is transposed + # from (M, S) to (S, M) for further use. + c = con.violation(x.T).T + + # The shape of c should be (M,), (1, M), or (S, M). Check for + # those shapes, as an incorrect shape indicates that the + # user constraint function didn't return the right thing, and + # the reshape operation will fail. Intercept the wrong shape + # to give a reasonable error message. I'm not sure what failure + # modes an inventive user will come up with. + if c.shape[-1] != con.num_constr or (S > 1 and c.shape[0] != S): + raise RuntimeError("An array returned from a Constraint has" + " the wrong shape. If `vectorized is False`" + " the Constraint should return an array of" + " shape (M,). If `vectorized is True` then" + " the Constraint must return an array of" + " shape (M, S), where S is the number of" + " solution vectors and M is the number of" + " constraint components in a given" + " Constraint object.") + + # the violation function may return a 1D array, but is it a + # sequence of constraints for one solution (S=1, M>=1), or the + # value of a single constraint for a sequence of solutions + # (S>=1, M=1) + c = np.reshape(c, (S, con.num_constr)) + _out[:, offset:offset + con.num_constr] = c + offset += con.num_constr + + return _out + + def _calculate_population_feasibilities(self, population): + """ + Calculate the feasibilities of a population. + + Parameters + ---------- + population : ndarray + An array of parameter vectors normalised to [0, 1] using lower + and upper limits. Has shape ``(np.size(population, 0), N)``. + + Returns + ------- + feasible, constraint_violation : ndarray, ndarray + Boolean array of feasibility for each population member, and an + array of the constraint violation for each population member. + constraint_violation has shape ``(np.size(population, 0), M)``, + where M is the number of constraints. + """ + num_members = np.size(population, 0) + if not self._wrapped_constraints: + # shortcut for no constraints + return np.ones(num_members, bool), np.zeros((num_members, 1)) + + # (S, N) + parameters_pop = self._scale_parameters(population) + + if self.vectorized: + # (S, M) + constraint_violation = np.array( + self._constraint_violation_fn(parameters_pop) + ) + else: + # (S, 1, M) + constraint_violation = np.array([self._constraint_violation_fn(x) + for x in parameters_pop]) + # if you use the list comprehension in the line above it will + # create an array of shape (S, 1, M), because each iteration + # generates an array of (1, M). In comparison the vectorized + # version returns (S, M). It's therefore necessary to remove axis 1 + constraint_violation = constraint_violation[:, 0] + + feasible = ~(np.sum(constraint_violation, axis=1) > 0) + + return feasible, constraint_violation + + def __iter__(self): + return self + + def __enter__(self): + return self + + def __exit__(self, *args): + return self._mapwrapper.__exit__(*args) + + def _accept_trial(self, energy_trial, feasible_trial, cv_trial, + energy_orig, feasible_orig, cv_orig): + """ + Trial is accepted if: + * it satisfies all constraints and provides a lower or equal objective + function value, while both the compared solutions are feasible + - or - + * it is feasible while the original solution is infeasible, + - or - + * it is infeasible, but provides a lower or equal constraint violation + for all constraint functions. + + This test corresponds to section III of Lampinen [1]_. + + Parameters + ---------- + energy_trial : float + Energy of the trial solution + feasible_trial : float + Feasibility of trial solution + cv_trial : array-like + Excess constraint violation for the trial solution + energy_orig : float + Energy of the original solution + feasible_orig : float + Feasibility of original solution + cv_orig : array-like + Excess constraint violation for the original solution + + Returns + ------- + accepted : bool + + """ + if feasible_orig and feasible_trial: + return energy_trial <= energy_orig + elif feasible_trial and not feasible_orig: + return True + elif not feasible_trial and (cv_trial <= cv_orig).all(): + # cv_trial < cv_orig would imply that both trial and orig are not + # feasible + return True + + return False + + def __next__(self): + """ + Evolve the population by a single generation + + Returns + ------- + x : ndarray + The best solution from the solver. + fun : float + Value of objective function obtained from the best solution. + """ + # the population may have just been initialized (all entries are + # np.inf). If it has you have to calculate the initial energies + if np.all(np.isinf(self.population_energies)): + self.feasible, self.constraint_violation = ( + self._calculate_population_feasibilities(self.population)) + + # only need to work out population energies for those that are + # feasible + self.population_energies[self.feasible] = ( + self._calculate_population_energies( + self.population[self.feasible])) + + self._promote_lowest_energy() + + if self.dither is not None: + self.scale = self.random_number_generator.uniform(self.dither[0], + self.dither[1]) + + if self._updating == 'immediate': + # update best solution immediately + for candidate in range(self.num_population_members): + if self._nfev > self.maxfun: + raise StopIteration + + # create a trial solution + trial = self._mutate(candidate) + + # ensuring that it's in the range [0, 1) + self._ensure_constraint(trial) + + # scale from [0, 1) to the actual parameter value + parameters = self._scale_parameters(trial) + + # determine the energy of the objective function + if self._wrapped_constraints: + cv = self._constraint_violation_fn(parameters) + feasible = False + energy = np.inf + if not np.sum(cv) > 0: + # solution is feasible + feasible = True + energy = self.func(parameters) + self._nfev += 1 + else: + feasible = True + cv = np.atleast_2d([0.]) + energy = self.func(parameters) + self._nfev += 1 + + # compare trial and population member + if self._accept_trial(energy, feasible, cv, + self.population_energies[candidate], + self.feasible[candidate], + self.constraint_violation[candidate]): + self.population[candidate] = trial + self.population_energies[candidate] = np.squeeze(energy) + self.feasible[candidate] = feasible + self.constraint_violation[candidate] = cv + + # if the trial candidate is also better than the best + # solution then promote it. + if self._accept_trial(energy, feasible, cv, + self.population_energies[0], + self.feasible[0], + self.constraint_violation[0]): + self._promote_lowest_energy() + + elif self._updating == 'deferred': + # update best solution once per generation + if self._nfev >= self.maxfun: + raise StopIteration + + # 'deferred' approach, vectorised form. + # create trial solutions + trial_pop = self._mutate_many( + np.arange(self.num_population_members) + ) + + # enforce bounds + self._ensure_constraint(trial_pop) + + # determine the energies of the objective function, but only for + # feasible trials + feasible, cv = self._calculate_population_feasibilities(trial_pop) + trial_energies = np.full(self.num_population_members, np.inf) + + # only calculate for feasible entries + trial_energies[feasible] = self._calculate_population_energies( + trial_pop[feasible]) + + # which solutions are 'improved'? + loc = [self._accept_trial(*val) for val in + zip(trial_energies, feasible, cv, self.population_energies, + self.feasible, self.constraint_violation)] + loc = np.array(loc) + self.population = np.where(loc[:, np.newaxis], + trial_pop, + self.population) + self.population_energies = np.where(loc, + trial_energies, + self.population_energies) + self.feasible = np.where(loc, + feasible, + self.feasible) + self.constraint_violation = np.where(loc[:, np.newaxis], + cv, + self.constraint_violation) + + # make sure the best solution is updated if updating='deferred'. + # put the lowest energy into the best solution position. + self._promote_lowest_energy() + + return self.x, self.population_energies[0] + + def _scale_parameters(self, trial): + """Scale from a number between 0 and 1 to parameters.""" + # trial either has shape (N, ) or (L, N), where L is the number of + # solutions being scaled + scaled = self.__scale_arg1 + (trial - 0.5) * self.__scale_arg2 + if np.count_nonzero(self.integrality): + i = np.broadcast_to(self.integrality, scaled.shape) + scaled[i] = np.round(scaled[i]) + return scaled + + def _unscale_parameters(self, parameters): + """Scale from parameters to a number between 0 and 1.""" + return (parameters - self.__scale_arg1) * self.__recip_scale_arg2 + 0.5 + + def _ensure_constraint(self, trial): + """Make sure the parameters lie between the limits.""" + mask = np.bitwise_or(trial > 1, trial < 0) + if oob := np.count_nonzero(mask): + trial[mask] = self.random_number_generator.uniform(size=oob) + + def _mutate_custom(self, candidate): + rng = self.random_number_generator + msg = ( + "strategy must have signature" + " f(candidate: int, population: np.ndarray, rng=None) returning an" + " array of shape (N,)" + ) + _population = self._scale_parameters(self.population) + if not len(np.shape(candidate)): + # single entry in population + trial = self.strategy(candidate, _population, rng=rng) + if trial.shape != (self.parameter_count,): + raise RuntimeError(msg) + else: + S = candidate.shape[0] + trial = np.array( + [self.strategy(c, _population, rng=rng) for c in candidate], + dtype=float + ) + if trial.shape != (S, self.parameter_count): + raise RuntimeError(msg) + return self._unscale_parameters(trial) + + def _mutate_many(self, candidates): + """Create trial vectors based on a mutation strategy.""" + rng = self.random_number_generator + + S = len(candidates) + if callable(self.strategy): + return self._mutate_custom(candidates) + + trial = np.copy(self.population[candidates]) + samples = np.array([self._select_samples(c, 5) for c in candidates]) + + if self.strategy in ['currenttobest1exp', 'currenttobest1bin']: + bprime = self.mutation_func(candidates, samples) + else: + bprime = self.mutation_func(samples) + + fill_point = rng_integers(rng, self.parameter_count, size=S) + crossovers = rng.uniform(size=(S, self.parameter_count)) + crossovers = crossovers < self.cross_over_probability + if self.strategy in self._binomial: + # the last one is always from the bprime vector for binomial + # If you fill in modulo with a loop you have to set the last one to + # true. If you don't use a loop then you can have any random entry + # be True. + i = np.arange(S) + crossovers[i, fill_point[i]] = True + trial = np.where(crossovers, bprime, trial) + return trial + + elif self.strategy in self._exponential: + crossovers[..., 0] = True + for j in range(S): + i = 0 + init_fill = fill_point[j] + while (i < self.parameter_count and crossovers[j, i]): + trial[j, init_fill] = bprime[j, init_fill] + init_fill = (init_fill + 1) % self.parameter_count + i += 1 + + return trial + + def _mutate(self, candidate): + """Create a trial vector based on a mutation strategy.""" + rng = self.random_number_generator + + if callable(self.strategy): + return self._mutate_custom(candidate) + + fill_point = rng_integers(rng, self.parameter_count) + samples = self._select_samples(candidate, 5) + + trial = np.copy(self.population[candidate]) + + if self.strategy in ['currenttobest1exp', 'currenttobest1bin']: + bprime = self.mutation_func(candidate, samples) + else: + bprime = self.mutation_func(samples) + + crossovers = rng.uniform(size=self.parameter_count) + crossovers = crossovers < self.cross_over_probability + if self.strategy in self._binomial: + # the last one is always from the bprime vector for binomial + # If you fill in modulo with a loop you have to set the last one to + # true. If you don't use a loop then you can have any random entry + # be True. + crossovers[fill_point] = True + trial = np.where(crossovers, bprime, trial) + return trial + + elif self.strategy in self._exponential: + i = 0 + crossovers[0] = True + while i < self.parameter_count and crossovers[i]: + trial[fill_point] = bprime[fill_point] + fill_point = (fill_point + 1) % self.parameter_count + i += 1 + + return trial + + def _best1(self, samples): + """best1bin, best1exp""" + # samples.shape == (S, 5) + # or + # samples.shape(5,) + r0, r1 = samples[..., :2].T + return (self.population[0] + self.scale * + (self.population[r0] - self.population[r1])) + + def _rand1(self, samples): + """rand1bin, rand1exp""" + r0, r1, r2 = samples[..., :3].T + return (self.population[r0] + self.scale * + (self.population[r1] - self.population[r2])) + + def _randtobest1(self, samples): + """randtobest1bin, randtobest1exp""" + r0, r1, r2 = samples[..., :3].T + bprime = np.copy(self.population[r0]) + bprime += self.scale * (self.population[0] - bprime) + bprime += self.scale * (self.population[r1] - + self.population[r2]) + return bprime + + def _currenttobest1(self, candidate, samples): + """currenttobest1bin, currenttobest1exp""" + r0, r1 = samples[..., :2].T + bprime = (self.population[candidate] + self.scale * + (self.population[0] - self.population[candidate] + + self.population[r0] - self.population[r1])) + return bprime + + def _best2(self, samples): + """best2bin, best2exp""" + r0, r1, r2, r3 = samples[..., :4].T + bprime = (self.population[0] + self.scale * + (self.population[r0] + self.population[r1] - + self.population[r2] - self.population[r3])) + + return bprime + + def _rand2(self, samples): + """rand2bin, rand2exp""" + r0, r1, r2, r3, r4 = samples[..., :5].T + bprime = (self.population[r0] + self.scale * + (self.population[r1] + self.population[r2] - + self.population[r3] - self.population[r4])) + + return bprime + + def _select_samples(self, candidate, number_samples): + """ + obtain random integers from range(self.num_population_members), + without replacement. You can't have the original candidate either. + """ + self.random_number_generator.shuffle(self._random_population_index) + idxs = self._random_population_index[:number_samples + 1] + return idxs[idxs != candidate][:number_samples] + + +class _ConstraintWrapper: + """Object to wrap/evaluate user defined constraints. + + Very similar in practice to `PreparedConstraint`, except that no evaluation + of jac/hess is performed (explicit or implicit). + + If created successfully, it will contain the attributes listed below. + + Parameters + ---------- + constraint : {`NonlinearConstraint`, `LinearConstraint`, `Bounds`} + Constraint to check and prepare. + x0 : array_like + Initial vector of independent variables, shape (N,) + + Attributes + ---------- + fun : callable + Function defining the constraint wrapped by one of the convenience + classes. + bounds : 2-tuple + Contains lower and upper bounds for the constraints --- lb and ub. + These are converted to ndarray and have a size equal to the number of + the constraints. + + Notes + ----- + _ConstraintWrapper.fun and _ConstraintWrapper.violation can get sent + arrays of shape (N, S) or (N,), where S is the number of vectors of shape + (N,) to consider constraints for. + """ + def __init__(self, constraint, x0): + self.constraint = constraint + + if isinstance(constraint, NonlinearConstraint): + def fun(x): + x = np.asarray(x) + return np.atleast_1d(constraint.fun(x)) + elif isinstance(constraint, LinearConstraint): + def fun(x): + if issparse(constraint.A): + A = constraint.A + else: + A = np.atleast_2d(constraint.A) + + res = A.dot(x) + # x either has shape (N, S) or (N) + # (M, N) x (N, S) --> (M, S) + # (M, N) x (N,) --> (M,) + # However, if (M, N) is a matrix then: + # (M, N) * (N,) --> (M, 1), we need this to be (M,) + if x.ndim == 1 and res.ndim == 2: + # deal with case that constraint.A is an np.matrix + # see gh20041 + res = np.asarray(res)[:, 0] + + return res + elif isinstance(constraint, Bounds): + def fun(x): + return np.asarray(x) + else: + raise ValueError("`constraint` of an unknown type is passed.") + + self.fun = fun + + lb = np.asarray(constraint.lb, dtype=float) + ub = np.asarray(constraint.ub, dtype=float) + + x0 = np.asarray(x0) + + # find out the number of constraints + f0 = fun(x0) + self.num_constr = m = f0.size + self.parameter_count = x0.size + + if lb.ndim == 0: + lb = np.resize(lb, m) + if ub.ndim == 0: + ub = np.resize(ub, m) + + self.bounds = (lb, ub) + + def __call__(self, x): + return np.atleast_1d(self.fun(x)) + + def violation(self, x): + """How much the constraint is exceeded by. + + Parameters + ---------- + x : array-like + Vector of independent variables, (N, S), where N is number of + parameters and S is the number of solutions to be investigated. + + Returns + ------- + excess : array-like + How much the constraint is exceeded by, for each of the + constraints specified by `_ConstraintWrapper.fun`. + Has shape (M, S) where M is the number of constraint components. + """ + # expect ev to have shape (num_constr, S) or (num_constr,) + ev = self.fun(np.asarray(x)) + + try: + excess_lb = np.maximum(self.bounds[0] - ev.T, 0) + excess_ub = np.maximum(ev.T - self.bounds[1], 0) + except ValueError as e: + raise RuntimeError("An array returned from a Constraint has" + " the wrong shape. If `vectorized is False`" + " the Constraint should return an array of" + " shape (M,). If `vectorized is True` then" + " the Constraint must return an array of" + " shape (M, S), where S is the number of" + " solution vectors and M is the number of" + " constraint components in a given" + " Constraint object.") from e + + v = (excess_lb + excess_ub).T + return v diff --git a/llava_next/lib/python3.10/site-packages/scipy/optimize/_direct.cpython-310-x86_64-linux-gnu.so b/llava_next/lib/python3.10/site-packages/scipy/optimize/_direct.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..fe89bac4a6f6b828def53da54b5eac17d45a4019 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/scipy/optimize/_direct.cpython-310-x86_64-linux-gnu.so differ diff --git a/llava_next/lib/python3.10/site-packages/scipy/optimize/_dual_annealing.py b/llava_next/lib/python3.10/site-packages/scipy/optimize/_dual_annealing.py new file mode 100644 index 0000000000000000000000000000000000000000..9645c7967b96772463d4cbe41e905195273ba1ae --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/scipy/optimize/_dual_annealing.py @@ -0,0 +1,732 @@ +# Dual Annealing implementation. +# Copyright (c) 2018 Sylvain Gubian , +# Yang Xiang +# Author: Sylvain Gubian, Yang Xiang, PMP S.A. + +""" +A Dual Annealing global optimization algorithm +""" + +import numpy as np +from scipy.optimize import OptimizeResult +from scipy.optimize import minimize, Bounds +from scipy.special import gammaln +from scipy._lib._util import check_random_state +from scipy.optimize._constraints import new_bounds_to_old + +__all__ = ['dual_annealing'] + + +class VisitingDistribution: + """ + Class used to generate new coordinates based on the distorted + Cauchy-Lorentz distribution. Depending on the steps within the strategy + chain, the class implements the strategy for generating new location + changes. + + Parameters + ---------- + lb : array_like + A 1-D NumPy ndarray containing lower bounds of the generated + components. Neither NaN or inf are allowed. + ub : array_like + A 1-D NumPy ndarray containing upper bounds for the generated + components. Neither NaN or inf are allowed. + visiting_param : float + Parameter for visiting distribution. Default value is 2.62. + Higher values give the visiting distribution a heavier tail, this + makes the algorithm jump to a more distant region. + The value range is (1, 3]. Its value is fixed for the life of the + object. + rand_gen : {`~numpy.random.RandomState`, `~numpy.random.Generator`} + A `~numpy.random.RandomState`, `~numpy.random.Generator` object + for using the current state of the created random generator container. + + """ + TAIL_LIMIT = 1.e8 + MIN_VISIT_BOUND = 1.e-10 + + def __init__(self, lb, ub, visiting_param, rand_gen): + # if you wish to make _visiting_param adjustable during the life of + # the object then _factor2, _factor3, _factor5, _d1, _factor6 will + # have to be dynamically calculated in `visit_fn`. They're factored + # out here so they don't need to be recalculated all the time. + self._visiting_param = visiting_param + self.rand_gen = rand_gen + self.lower = lb + self.upper = ub + self.bound_range = ub - lb + + # these are invariant numbers unless visiting_param changes + self._factor2 = np.exp((4.0 - self._visiting_param) * np.log( + self._visiting_param - 1.0)) + self._factor3 = np.exp((2.0 - self._visiting_param) * np.log(2.0) + / (self._visiting_param - 1.0)) + self._factor4_p = np.sqrt(np.pi) * self._factor2 / (self._factor3 * ( + 3.0 - self._visiting_param)) + + self._factor5 = 1.0 / (self._visiting_param - 1.0) - 0.5 + self._d1 = 2.0 - self._factor5 + self._factor6 = np.pi * (1.0 - self._factor5) / np.sin( + np.pi * (1.0 - self._factor5)) / np.exp(gammaln(self._d1)) + + def visiting(self, x, step, temperature): + """ Based on the step in the strategy chain, new coordinates are + generated by changing all components is the same time or only + one of them, the new values are computed with visit_fn method + """ + dim = x.size + if step < dim: + # Changing all coordinates with a new visiting value + visits = self.visit_fn(temperature, dim) + upper_sample, lower_sample = self.rand_gen.uniform(size=2) + visits[visits > self.TAIL_LIMIT] = self.TAIL_LIMIT * upper_sample + visits[visits < -self.TAIL_LIMIT] = -self.TAIL_LIMIT * lower_sample + x_visit = visits + x + a = x_visit - self.lower + b = np.fmod(a, self.bound_range) + self.bound_range + x_visit = np.fmod(b, self.bound_range) + self.lower + x_visit[np.fabs( + x_visit - self.lower) < self.MIN_VISIT_BOUND] += 1.e-10 + else: + # Changing only one coordinate at a time based on strategy + # chain step + x_visit = np.copy(x) + visit = self.visit_fn(temperature, 1)[0] + if visit > self.TAIL_LIMIT: + visit = self.TAIL_LIMIT * self.rand_gen.uniform() + elif visit < -self.TAIL_LIMIT: + visit = -self.TAIL_LIMIT * self.rand_gen.uniform() + index = step - dim + x_visit[index] = visit + x[index] + a = x_visit[index] - self.lower[index] + b = np.fmod(a, self.bound_range[index]) + self.bound_range[index] + x_visit[index] = np.fmod(b, self.bound_range[ + index]) + self.lower[index] + if np.fabs(x_visit[index] - self.lower[ + index]) < self.MIN_VISIT_BOUND: + x_visit[index] += self.MIN_VISIT_BOUND + return x_visit + + def visit_fn(self, temperature, dim): + """ Formula Visita from p. 405 of reference [2] """ + x, y = self.rand_gen.normal(size=(dim, 2)).T + + factor1 = np.exp(np.log(temperature) / (self._visiting_param - 1.0)) + factor4 = self._factor4_p * factor1 + + # sigmax + x *= np.exp(-(self._visiting_param - 1.0) * np.log( + self._factor6 / factor4) / (3.0 - self._visiting_param)) + + den = np.exp((self._visiting_param - 1.0) * np.log(np.fabs(y)) / + (3.0 - self._visiting_param)) + + return x / den + + +class EnergyState: + """ + Class used to record the energy state. At any time, it knows what is the + currently used coordinates and the most recent best location. + + Parameters + ---------- + lower : array_like + A 1-D NumPy ndarray containing lower bounds for generating an initial + random components in the `reset` method. + upper : array_like + A 1-D NumPy ndarray containing upper bounds for generating an initial + random components in the `reset` method + components. Neither NaN or inf are allowed. + callback : callable, ``callback(x, f, context)``, optional + A callback function which will be called for all minima found. + ``x`` and ``f`` are the coordinates and function value of the + latest minimum found, and `context` has value in [0, 1, 2] + """ + # Maximum number of trials for generating a valid starting point + MAX_REINIT_COUNT = 1000 + + def __init__(self, lower, upper, callback=None): + self.ebest = None + self.current_energy = None + self.current_location = None + self.xbest = None + self.lower = lower + self.upper = upper + self.callback = callback + + def reset(self, func_wrapper, rand_gen, x0=None): + """ + Initialize current location is the search domain. If `x0` is not + provided, a random location within the bounds is generated. + """ + if x0 is None: + self.current_location = rand_gen.uniform(self.lower, self.upper, + size=len(self.lower)) + else: + self.current_location = np.copy(x0) + init_error = True + reinit_counter = 0 + while init_error: + self.current_energy = func_wrapper.fun(self.current_location) + if self.current_energy is None: + raise ValueError('Objective function is returning None') + if (not np.isfinite(self.current_energy) or np.isnan( + self.current_energy)): + if reinit_counter >= EnergyState.MAX_REINIT_COUNT: + init_error = False + message = ( + 'Stopping algorithm because function ' + 'create NaN or (+/-) infinity values even with ' + 'trying new random parameters' + ) + raise ValueError(message) + self.current_location = rand_gen.uniform(self.lower, + self.upper, + size=self.lower.size) + reinit_counter += 1 + else: + init_error = False + # If first time reset, initialize ebest and xbest + if self.ebest is None and self.xbest is None: + self.ebest = self.current_energy + self.xbest = np.copy(self.current_location) + # Otherwise, we keep them in case of reannealing reset + + def update_best(self, e, x, context): + self.ebest = e + self.xbest = np.copy(x) + if self.callback is not None: + val = self.callback(x, e, context) + if val is not None: + if val: + return ('Callback function requested to stop early by ' + 'returning True') + + def update_current(self, e, x): + self.current_energy = e + self.current_location = np.copy(x) + + +class StrategyChain: + """ + Class that implements within a Markov chain the strategy for location + acceptance and local search decision making. + + Parameters + ---------- + acceptance_param : float + Parameter for acceptance distribution. It is used to control the + probability of acceptance. The lower the acceptance parameter, the + smaller the probability of acceptance. Default value is -5.0 with + a range (-1e4, -5]. + visit_dist : VisitingDistribution + Instance of `VisitingDistribution` class. + func_wrapper : ObjectiveFunWrapper + Instance of `ObjectiveFunWrapper` class. + minimizer_wrapper: LocalSearchWrapper + Instance of `LocalSearchWrapper` class. + rand_gen : {None, int, `numpy.random.Generator`, + `numpy.random.RandomState`}, optional + + If `seed` is None (or `np.random`), the `numpy.random.RandomState` + singleton is used. + If `seed` is an int, a new ``RandomState`` instance is used, + seeded with `seed`. + If `seed` is already a ``Generator`` or ``RandomState`` instance then + that instance is used. + energy_state: EnergyState + Instance of `EnergyState` class. + + """ + + def __init__(self, acceptance_param, visit_dist, func_wrapper, + minimizer_wrapper, rand_gen, energy_state): + # Local strategy chain minimum energy and location + self.emin = energy_state.current_energy + self.xmin = np.array(energy_state.current_location) + # Global optimizer state + self.energy_state = energy_state + # Acceptance parameter + self.acceptance_param = acceptance_param + # Visiting distribution instance + self.visit_dist = visit_dist + # Wrapper to objective function + self.func_wrapper = func_wrapper + # Wrapper to the local minimizer + self.minimizer_wrapper = minimizer_wrapper + self.not_improved_idx = 0 + self.not_improved_max_idx = 1000 + self._rand_gen = rand_gen + self.temperature_step = 0 + self.K = 100 * len(energy_state.current_location) + + def accept_reject(self, j, e, x_visit): + r = self._rand_gen.uniform() + pqv_temp = 1.0 - ((1.0 - self.acceptance_param) * + (e - self.energy_state.current_energy) / self.temperature_step) + if pqv_temp <= 0.: + pqv = 0. + else: + pqv = np.exp(np.log(pqv_temp) / ( + 1. - self.acceptance_param)) + + if r <= pqv: + # We accept the new location and update state + self.energy_state.update_current(e, x_visit) + self.xmin = np.copy(self.energy_state.current_location) + + # No improvement for a long time + if self.not_improved_idx >= self.not_improved_max_idx: + if j == 0 or self.energy_state.current_energy < self.emin: + self.emin = self.energy_state.current_energy + self.xmin = np.copy(self.energy_state.current_location) + + def run(self, step, temperature): + self.temperature_step = temperature / float(step + 1) + self.not_improved_idx += 1 + for j in range(self.energy_state.current_location.size * 2): + if j == 0: + if step == 0: + self.energy_state_improved = True + else: + self.energy_state_improved = False + x_visit = self.visit_dist.visiting( + self.energy_state.current_location, j, temperature) + # Calling the objective function + e = self.func_wrapper.fun(x_visit) + if e < self.energy_state.current_energy: + # We have got a better energy value + self.energy_state.update_current(e, x_visit) + if e < self.energy_state.ebest: + val = self.energy_state.update_best(e, x_visit, 0) + if val is not None: + if val: + return val + self.energy_state_improved = True + self.not_improved_idx = 0 + else: + # We have not improved but do we accept the new location? + self.accept_reject(j, e, x_visit) + if self.func_wrapper.nfev >= self.func_wrapper.maxfun: + return ('Maximum number of function call reached ' + 'during annealing') + # End of StrategyChain loop + + def local_search(self): + # Decision making for performing a local search + # based on strategy chain results + # If energy has been improved or no improvement since too long, + # performing a local search with the best strategy chain location + if self.energy_state_improved: + # Global energy has improved, let's see if LS improves further + e, x = self.minimizer_wrapper.local_search(self.energy_state.xbest, + self.energy_state.ebest) + if e < self.energy_state.ebest: + self.not_improved_idx = 0 + val = self.energy_state.update_best(e, x, 1) + if val is not None: + if val: + return val + self.energy_state.update_current(e, x) + if self.func_wrapper.nfev >= self.func_wrapper.maxfun: + return ('Maximum number of function call reached ' + 'during local search') + # Check probability of a need to perform a LS even if no improvement + do_ls = False + if self.K < 90 * len(self.energy_state.current_location): + pls = np.exp(self.K * ( + self.energy_state.ebest - self.energy_state.current_energy) / + self.temperature_step) + if pls >= self._rand_gen.uniform(): + do_ls = True + # Global energy not improved, let's see what LS gives + # on the best strategy chain location + if self.not_improved_idx >= self.not_improved_max_idx: + do_ls = True + if do_ls: + e, x = self.minimizer_wrapper.local_search(self.xmin, self.emin) + self.xmin = np.copy(x) + self.emin = e + self.not_improved_idx = 0 + self.not_improved_max_idx = self.energy_state.current_location.size + if e < self.energy_state.ebest: + val = self.energy_state.update_best( + self.emin, self.xmin, 2) + if val is not None: + if val: + return val + self.energy_state.update_current(e, x) + if self.func_wrapper.nfev >= self.func_wrapper.maxfun: + return ('Maximum number of function call reached ' + 'during dual annealing') + + +class ObjectiveFunWrapper: + + def __init__(self, func, maxfun=1e7, *args): + self.func = func + self.args = args + # Number of objective function evaluations + self.nfev = 0 + # Number of gradient function evaluation if used + self.ngev = 0 + # Number of hessian of the objective function if used + self.nhev = 0 + self.maxfun = maxfun + + def fun(self, x): + self.nfev += 1 + return self.func(x, *self.args) + + +class LocalSearchWrapper: + """ + Class used to wrap around the minimizer used for local search + Default local minimizer is SciPy minimizer L-BFGS-B + """ + + LS_MAXITER_RATIO = 6 + LS_MAXITER_MIN = 100 + LS_MAXITER_MAX = 1000 + + def __init__(self, search_bounds, func_wrapper, *args, **kwargs): + self.func_wrapper = func_wrapper + self.kwargs = kwargs + self.jac = self.kwargs.get('jac', None) + self.hess = self.kwargs.get('hess', None) + self.hessp = self.kwargs.get('hessp', None) + self.kwargs.pop("args", None) + self.minimizer = minimize + bounds_list = list(zip(*search_bounds)) + self.lower = np.array(bounds_list[0]) + self.upper = np.array(bounds_list[1]) + + # If no minimizer specified, use SciPy minimize with 'L-BFGS-B' method + if not self.kwargs: + n = len(self.lower) + ls_max_iter = min(max(n * self.LS_MAXITER_RATIO, + self.LS_MAXITER_MIN), + self.LS_MAXITER_MAX) + self.kwargs['method'] = 'L-BFGS-B' + self.kwargs['options'] = { + 'maxiter': ls_max_iter, + } + self.kwargs['bounds'] = list(zip(self.lower, self.upper)) + else: + if callable(self.jac): + def wrapped_jac(x): + return self.jac(x, *args) + self.kwargs['jac'] = wrapped_jac + if callable(self.hess): + def wrapped_hess(x): + return self.hess(x, *args) + self.kwargs['hess'] = wrapped_hess + if callable(self.hessp): + def wrapped_hessp(x, p): + return self.hessp(x, p, *args) + self.kwargs['hessp'] = wrapped_hessp + + def local_search(self, x, e): + # Run local search from the given x location where energy value is e + x_tmp = np.copy(x) + mres = self.minimizer(self.func_wrapper.fun, x, **self.kwargs) + if 'njev' in mres: + self.func_wrapper.ngev += mres.njev + if 'nhev' in mres: + self.func_wrapper.nhev += mres.nhev + # Check if is valid value + is_finite = np.all(np.isfinite(mres.x)) and np.isfinite(mres.fun) + in_bounds = np.all(mres.x >= self.lower) and np.all( + mres.x <= self.upper) + is_valid = is_finite and in_bounds + + # Use the new point only if it is valid and return a better results + if is_valid and mres.fun < e: + return mres.fun, mres.x + else: + return e, x_tmp + + +def dual_annealing(func, bounds, args=(), maxiter=1000, + minimizer_kwargs=None, initial_temp=5230., + restart_temp_ratio=2.e-5, visit=2.62, accept=-5.0, + maxfun=1e7, seed=None, no_local_search=False, + callback=None, x0=None): + """ + Find the global minimum of a function using Dual Annealing. + + Parameters + ---------- + func : callable + The objective function to be minimized. Must be in the form + ``f(x, *args)``, where ``x`` is the argument in the form of a 1-D array + and ``args`` is a tuple of any additional fixed parameters needed to + completely specify the function. + bounds : sequence or `Bounds` + Bounds for variables. There are two ways to specify the bounds: + + 1. Instance of `Bounds` class. + 2. Sequence of ``(min, max)`` pairs for each element in `x`. + + args : tuple, optional + Any additional fixed parameters needed to completely specify the + objective function. + maxiter : int, optional + The maximum number of global search iterations. Default value is 1000. + minimizer_kwargs : dict, optional + Keyword arguments to be passed to the local minimizer + (`minimize`). An important option could be ``method`` for the minimizer + method to use. + If no keyword arguments are provided, the local minimizer defaults to + 'L-BFGS-B' and uses the already supplied bounds. If `minimizer_kwargs` + is specified, then the dict must contain all parameters required to + control the local minimization. `args` is ignored in this dict, as it is + passed automatically. `bounds` is not automatically passed on to the + local minimizer as the method may not support them. + initial_temp : float, optional + The initial temperature, use higher values to facilitates a wider + search of the energy landscape, allowing dual_annealing to escape + local minima that it is trapped in. Default value is 5230. Range is + (0.01, 5.e4]. + restart_temp_ratio : float, optional + During the annealing process, temperature is decreasing, when it + reaches ``initial_temp * restart_temp_ratio``, the reannealing process + is triggered. Default value of the ratio is 2e-5. Range is (0, 1). + visit : float, optional + Parameter for visiting distribution. Default value is 2.62. Higher + values give the visiting distribution a heavier tail, this makes + the algorithm jump to a more distant region. The value range is (1, 3]. + accept : float, optional + Parameter for acceptance distribution. It is used to control the + probability of acceptance. The lower the acceptance parameter, the + smaller the probability of acceptance. Default value is -5.0 with + a range (-1e4, -5]. + maxfun : int, optional + Soft limit for the number of objective function calls. If the + algorithm is in the middle of a local search, this number will be + exceeded, the algorithm will stop just after the local search is + done. Default value is 1e7. + seed : {None, int, `numpy.random.Generator`, `numpy.random.RandomState`}, optional + If `seed` is None (or `np.random`), the `numpy.random.RandomState` + singleton is used. + If `seed` is an int, a new ``RandomState`` instance is used, + seeded with `seed`. + If `seed` is already a ``Generator`` or ``RandomState`` instance then + that instance is used. + Specify `seed` for repeatable minimizations. The random numbers + generated with this seed only affect the visiting distribution function + and new coordinates generation. + no_local_search : bool, optional + If `no_local_search` is set to True, a traditional Generalized + Simulated Annealing will be performed with no local search + strategy applied. + callback : callable, optional + A callback function with signature ``callback(x, f, context)``, + which will be called for all minima found. + ``x`` and ``f`` are the coordinates and function value of the + latest minimum found, and ``context`` has value in [0, 1, 2], with the + following meaning: + + - 0: minimum detected in the annealing process. + - 1: detection occurred in the local search process. + - 2: detection done in the dual annealing process. + + If the callback implementation returns True, the algorithm will stop. + x0 : ndarray, shape(n,), optional + Coordinates of a single N-D starting point. + + Returns + ------- + res : OptimizeResult + The optimization result represented as a `OptimizeResult` object. + Important attributes are: ``x`` the solution array, ``fun`` the value + of the function at the solution, and ``message`` which describes the + cause of the termination. + See `OptimizeResult` for a description of other attributes. + + Notes + ----- + This function implements the Dual Annealing optimization. This stochastic + approach derived from [3]_ combines the generalization of CSA (Classical + Simulated Annealing) and FSA (Fast Simulated Annealing) [1]_ [2]_ coupled + to a strategy for applying a local search on accepted locations [4]_. + An alternative implementation of this same algorithm is described in [5]_ + and benchmarks are presented in [6]_. This approach introduces an advanced + method to refine the solution found by the generalized annealing + process. This algorithm uses a distorted Cauchy-Lorentz visiting + distribution, with its shape controlled by the parameter :math:`q_{v}` + + .. math:: + + g_{q_{v}}(\\Delta x(t)) \\propto \\frac{ \\ + \\left[T_{q_{v}}(t) \\right]^{-\\frac{D}{3-q_{v}}}}{ \\ + \\left[{1+(q_{v}-1)\\frac{(\\Delta x(t))^{2}} { \\ + \\left[T_{q_{v}}(t)\\right]^{\\frac{2}{3-q_{v}}}}}\\right]^{ \\ + \\frac{1}{q_{v}-1}+\\frac{D-1}{2}}} + + Where :math:`t` is the artificial time. This visiting distribution is used + to generate a trial jump distance :math:`\\Delta x(t)` of variable + :math:`x(t)` under artificial temperature :math:`T_{q_{v}}(t)`. + + From the starting point, after calling the visiting distribution + function, the acceptance probability is computed as follows: + + .. math:: + + p_{q_{a}} = \\min{\\{1,\\left[1-(1-q_{a}) \\beta \\Delta E \\right]^{ \\ + \\frac{1}{1-q_{a}}}\\}} + + Where :math:`q_{a}` is a acceptance parameter. For :math:`q_{a}<1`, zero + acceptance probability is assigned to the cases where + + .. math:: + + [1-(1-q_{a}) \\beta \\Delta E] < 0 + + The artificial temperature :math:`T_{q_{v}}(t)` is decreased according to + + .. math:: + + T_{q_{v}}(t) = T_{q_{v}}(1) \\frac{2^{q_{v}-1}-1}{\\left( \\ + 1 + t\\right)^{q_{v}-1}-1} + + Where :math:`q_{v}` is the visiting parameter. + + .. versionadded:: 1.2.0 + + References + ---------- + .. [1] Tsallis C. Possible generalization of Boltzmann-Gibbs + statistics. Journal of Statistical Physics, 52, 479-487 (1998). + .. [2] Tsallis C, Stariolo DA. Generalized Simulated Annealing. + Physica A, 233, 395-406 (1996). + .. [3] Xiang Y, Sun DY, Fan W, Gong XG. Generalized Simulated + Annealing Algorithm and Its Application to the Thomson Model. + Physics Letters A, 233, 216-220 (1997). + .. [4] Xiang Y, Gong XG. Efficiency of Generalized Simulated + Annealing. Physical Review E, 62, 4473 (2000). + .. [5] Xiang Y, Gubian S, Suomela B, Hoeng J. Generalized + Simulated Annealing for Efficient Global Optimization: the GenSA + Package for R. The R Journal, Volume 5/1 (2013). + .. [6] Mullen, K. Continuous Global Optimization in R. Journal of + Statistical Software, 60(6), 1 - 45, (2014). + :doi:`10.18637/jss.v060.i06` + + Examples + -------- + The following example is a 10-D problem, with many local minima. + The function involved is called Rastrigin + (https://en.wikipedia.org/wiki/Rastrigin_function) + + >>> import numpy as np + >>> from scipy.optimize import dual_annealing + >>> func = lambda x: np.sum(x*x - 10*np.cos(2*np.pi*x)) + 10*np.size(x) + >>> lw = [-5.12] * 10 + >>> up = [5.12] * 10 + >>> ret = dual_annealing(func, bounds=list(zip(lw, up))) + >>> ret.x + array([-4.26437714e-09, -3.91699361e-09, -1.86149218e-09, -3.97165720e-09, + -6.29151648e-09, -6.53145322e-09, -3.93616815e-09, -6.55623025e-09, + -6.05775280e-09, -5.00668935e-09]) # random + >>> ret.fun + 0.000000 + + """ + + if isinstance(bounds, Bounds): + bounds = new_bounds_to_old(bounds.lb, bounds.ub, len(bounds.lb)) + + if x0 is not None and not len(x0) == len(bounds): + raise ValueError('Bounds size does not match x0') + + lu = list(zip(*bounds)) + lower = np.array(lu[0]) + upper = np.array(lu[1]) + # Check that restart temperature ratio is correct + if restart_temp_ratio <= 0. or restart_temp_ratio >= 1.: + raise ValueError('Restart temperature ratio has to be in range (0, 1)') + # Checking bounds are valid + if (np.any(np.isinf(lower)) or np.any(np.isinf(upper)) or np.any( + np.isnan(lower)) or np.any(np.isnan(upper))): + raise ValueError('Some bounds values are inf values or nan values') + # Checking that bounds are consistent + if not np.all(lower < upper): + raise ValueError('Bounds are not consistent min < max') + # Checking that bounds are the same length + if not len(lower) == len(upper): + raise ValueError('Bounds do not have the same dimensions') + + # Wrapper for the objective function + func_wrapper = ObjectiveFunWrapper(func, maxfun, *args) + + # minimizer_kwargs has to be a dict, not None + minimizer_kwargs = minimizer_kwargs or {} + + minimizer_wrapper = LocalSearchWrapper( + bounds, func_wrapper, *args, **minimizer_kwargs) + + # Initialization of random Generator for reproducible runs if seed provided + rand_state = check_random_state(seed) + # Initialization of the energy state + energy_state = EnergyState(lower, upper, callback) + energy_state.reset(func_wrapper, rand_state, x0) + # Minimum value of annealing temperature reached to perform + # re-annealing + temperature_restart = initial_temp * restart_temp_ratio + # VisitingDistribution instance + visit_dist = VisitingDistribution(lower, upper, visit, rand_state) + # Strategy chain instance + strategy_chain = StrategyChain(accept, visit_dist, func_wrapper, + minimizer_wrapper, rand_state, energy_state) + need_to_stop = False + iteration = 0 + message = [] + # OptimizeResult object to be returned + optimize_res = OptimizeResult() + optimize_res.success = True + optimize_res.status = 0 + + t1 = np.exp((visit - 1) * np.log(2.0)) - 1.0 + # Run the search loop + while not need_to_stop: + for i in range(maxiter): + # Compute temperature for this step + s = float(i) + 2.0 + t2 = np.exp((visit - 1) * np.log(s)) - 1.0 + temperature = initial_temp * t1 / t2 + if iteration >= maxiter: + message.append("Maximum number of iteration reached") + need_to_stop = True + break + # Need a re-annealing process? + if temperature < temperature_restart: + energy_state.reset(func_wrapper, rand_state) + break + # starting strategy chain + val = strategy_chain.run(i, temperature) + if val is not None: + message.append(val) + need_to_stop = True + optimize_res.success = False + break + # Possible local search at the end of the strategy chain + if not no_local_search: + val = strategy_chain.local_search() + if val is not None: + message.append(val) + need_to_stop = True + optimize_res.success = False + break + iteration += 1 + + # Setting the OptimizeResult values + optimize_res.x = energy_state.xbest + optimize_res.fun = energy_state.ebest + optimize_res.nit = iteration + optimize_res.nfev = func_wrapper.nfev + optimize_res.njev = func_wrapper.ngev + optimize_res.nhev = func_wrapper.nhev + optimize_res.message = message + return optimize_res diff --git a/llava_next/lib/python3.10/site-packages/scipy/optimize/_isotonic.py b/llava_next/lib/python3.10/site-packages/scipy/optimize/_isotonic.py new file mode 100644 index 0000000000000000000000000000000000000000..bbbce625a7e5f9befd53bd4b5a1d043e71537bee --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/scipy/optimize/_isotonic.py @@ -0,0 +1,158 @@ +from __future__ import annotations +from typing import TYPE_CHECKING + +import numpy as np + +from ._optimize import OptimizeResult +from ._pava_pybind import pava + +if TYPE_CHECKING: + import numpy.typing as npt + + +__all__ = ["isotonic_regression"] + + +def isotonic_regression( + y: npt.ArrayLike, + *, + weights: npt.ArrayLike | None = None, + increasing: bool = True, +) -> OptimizeResult: + r"""Nonparametric isotonic regression. + + A (not strictly) monotonically increasing array `x` with the same length + as `y` is calculated by the pool adjacent violators algorithm (PAVA), see + [1]_. See the Notes section for more details. + + Parameters + ---------- + y : (N,) array_like + Response variable. + weights : (N,) array_like or None + Case weights. + increasing : bool + If True, fit monotonic increasing, i.e. isotonic, regression. + If False, fit a monotonic decreasing, i.e. antitonic, regression. + Default is True. + + Returns + ------- + res : OptimizeResult + The optimization result represented as a ``OptimizeResult`` object. + Important attributes are: + + - ``x``: The isotonic regression solution, i.e. an increasing (or + decreasing) array of the same length than y, with elements in the + range from min(y) to max(y). + - ``weights`` : Array with the sum of case weights for each block + (or pool) B. + - ``blocks``: Array of length B+1 with the indices of the start + positions of each block (or pool) B. The j-th block is given by + ``x[blocks[j]:blocks[j+1]]`` for which all values are the same. + + Notes + ----- + Given data :math:`y` and case weights :math:`w`, the isotonic regression + solves the following optimization problem: + + .. math:: + + \operatorname{argmin}_{x_i} \sum_i w_i (y_i - x_i)^2 \quad + \text{subject to } x_i \leq x_j \text{ whenever } i \leq j \,. + + For every input value :math:`y_i`, it generates a value :math:`x_i` such + that :math:`x` is increasing (but not strictly), i.e. + :math:`x_i \leq x_{i+1}`. This is accomplished by the PAVA. + The solution consists of pools or blocks, i.e. neighboring elements of + :math:`x`, e.g. :math:`x_i` and :math:`x_{i+1}`, that all have the same + value. + + Most interestingly, the solution stays the same if the squared loss is + replaced by the wide class of Bregman functions which are the unique + class of strictly consistent scoring functions for the mean, see [2]_ + and references therein. + + The implemented version of PAVA according to [1]_ has a computational + complexity of O(N) with input size N. + + References + ---------- + .. [1] Busing, F. M. T. A. (2022). + Monotone Regression: A Simple and Fast O(n) PAVA Implementation. + Journal of Statistical Software, Code Snippets, 102(1), 1-25. + :doi:`10.18637/jss.v102.c01` + .. [2] Jordan, A.I., Mühlemann, A. & Ziegel, J.F. + Characterizing the optimal solutions to the isotonic regression + problem for identifiable functionals. + Ann Inst Stat Math 74, 489-514 (2022). + :doi:`10.1007/s10463-021-00808-0` + + Examples + -------- + This example demonstrates that ``isotonic_regression`` really solves a + constrained optimization problem. + + >>> import numpy as np + >>> from scipy.optimize import isotonic_regression, minimize + >>> y = [1.5, 1.0, 4.0, 6.0, 5.7, 5.0, 7.8, 9.0, 7.5, 9.5, 9.0] + >>> def objective(yhat, y): + ... return np.sum((yhat - y)**2) + >>> def constraint(yhat, y): + ... # This is for a monotonically increasing regression. + ... return np.diff(yhat) + >>> result = minimize(objective, x0=y, args=(y,), + ... constraints=[{'type': 'ineq', + ... 'fun': lambda x: constraint(x, y)}]) + >>> result.x + array([1.25 , 1.25 , 4. , 5.56666667, 5.56666667, + 5.56666667, 7.8 , 8.25 , 8.25 , 9.25 , + 9.25 ]) + >>> result = isotonic_regression(y) + >>> result.x + array([1.25 , 1.25 , 4. , 5.56666667, 5.56666667, + 5.56666667, 7.8 , 8.25 , 8.25 , 9.25 , + 9.25 ]) + + The big advantage of ``isotonic_regression`` compared to calling + ``minimize`` is that it is more user friendly, i.e. one does not need to + define objective and constraint functions, and that it is orders of + magnitudes faster. On commodity hardware (in 2023), for normal distributed + input y of length 1000, the minimizer takes about 4 seconds, while + ``isotonic_regression`` takes about 200 microseconds. + """ + yarr = np.atleast_1d(y) # Check yarr.ndim == 1 is implicit (pybind11) in pava. + order = slice(None) if increasing else slice(None, None, -1) + x = np.array(yarr[order], order="C", dtype=np.float64, copy=True) + if weights is None: + wx = np.ones_like(yarr, dtype=np.float64) + else: + warr = np.atleast_1d(weights) + + if not (yarr.ndim == warr.ndim == 1 and yarr.shape[0] == warr.shape[0]): + raise ValueError( + "Input arrays y and w must have one dimension of equal length." + ) + if np.any(warr <= 0): + raise ValueError("Weights w must be strictly positive.") + + wx = np.array(warr[order], order="C", dtype=np.float64, copy=True) + n = x.shape[0] + r = np.full(shape=n + 1, fill_value=-1, dtype=np.intp) + x, wx, r, b = pava(x, wx, r) + # Now that we know the number of blocks b, we only keep the relevant part + # of r and wx. + # As information: Due to the pava implementation, after the last block + # index, there might be smaller numbers appended to r, e.g. + # r = [0, 10, 8, 7] which in the end should be r = [0, 10]. + r = r[:b + 1] + wx = wx[:b] + if not increasing: + x = x[::-1] + wx = wx[::-1] + r = r[-1] - r[::-1] + return OptimizeResult( + x=x, + weights=wx, + blocks=r, + ) diff --git a/llava_next/lib/python3.10/site-packages/scipy/optimize/_lbfgsb_py.py b/llava_next/lib/python3.10/site-packages/scipy/optimize/_lbfgsb_py.py new file mode 100644 index 0000000000000000000000000000000000000000..42ad9038ef0ce4c29b0cf22c5c9d2a1c029827c3 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/scipy/optimize/_lbfgsb_py.py @@ -0,0 +1,543 @@ +""" +Functions +--------- +.. autosummary:: + :toctree: generated/ + + fmin_l_bfgs_b + +""" + +## License for the Python wrapper +## ============================== + +## Copyright (c) 2004 David M. Cooke + +## Permission is hereby granted, free of charge, to any person obtaining a +## copy of this software and associated documentation files (the "Software"), +## to deal in the Software without restriction, including without limitation +## the rights to use, copy, modify, merge, publish, distribute, sublicense, +## and/or sell copies of the Software, and to permit persons to whom the +## Software is furnished to do so, subject to the following conditions: + +## The above copyright notice and this permission notice shall be included in +## all copies or substantial portions of the Software. + +## THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +## IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +## FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +## AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +## LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +## FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +## DEALINGS IN THE SOFTWARE. + +## Modifications by Travis Oliphant and Enthought, Inc. for inclusion in SciPy + +import numpy as np +from numpy import array, asarray, float64, zeros +from . import _lbfgsb +from ._optimize import (MemoizeJac, OptimizeResult, _call_callback_maybe_halt, + _wrap_callback, _check_unknown_options, + _prepare_scalar_function) +from ._constraints import old_bound_to_new + +from scipy.sparse.linalg import LinearOperator + +__all__ = ['fmin_l_bfgs_b', 'LbfgsInvHessProduct'] + + +def fmin_l_bfgs_b(func, x0, fprime=None, args=(), + approx_grad=0, + bounds=None, m=10, factr=1e7, pgtol=1e-5, + epsilon=1e-8, + iprint=-1, maxfun=15000, maxiter=15000, disp=None, + callback=None, maxls=20): + """ + Minimize a function func using the L-BFGS-B algorithm. + + Parameters + ---------- + func : callable f(x,*args) + Function to minimize. + x0 : ndarray + Initial guess. + fprime : callable fprime(x,*args), optional + The gradient of `func`. If None, then `func` returns the function + value and the gradient (``f, g = func(x, *args)``), unless + `approx_grad` is True in which case `func` returns only ``f``. + args : sequence, optional + Arguments to pass to `func` and `fprime`. + approx_grad : bool, optional + Whether to approximate the gradient numerically (in which case + `func` returns only the function value). + bounds : list, optional + ``(min, max)`` pairs for each element in ``x``, defining + the bounds on that parameter. Use None or +-inf for one of ``min`` or + ``max`` when there is no bound in that direction. + m : int, optional + The maximum number of variable metric corrections + used to define the limited memory matrix. (The limited memory BFGS + method does not store the full hessian but uses this many terms in an + approximation to it.) + factr : float, optional + The iteration stops when + ``(f^k - f^{k+1})/max{|f^k|,|f^{k+1}|,1} <= factr * eps``, + where ``eps`` is the machine precision, which is automatically + generated by the code. Typical values for `factr` are: 1e12 for + low accuracy; 1e7 for moderate accuracy; 10.0 for extremely + high accuracy. See Notes for relationship to `ftol`, which is exposed + (instead of `factr`) by the `scipy.optimize.minimize` interface to + L-BFGS-B. + pgtol : float, optional + The iteration will stop when + ``max{|proj g_i | i = 1, ..., n} <= pgtol`` + where ``proj g_i`` is the i-th component of the projected gradient. + epsilon : float, optional + Step size used when `approx_grad` is True, for numerically + calculating the gradient + iprint : int, optional + Controls the frequency of output. ``iprint < 0`` means no output; + ``iprint = 0`` print only one line at the last iteration; + ``0 < iprint < 99`` print also f and ``|proj g|`` every iprint iterations; + ``iprint = 99`` print details of every iteration except n-vectors; + ``iprint = 100`` print also the changes of active set and final x; + ``iprint > 100`` print details of every iteration including x and g. + disp : int, optional + If zero, then no output. If a positive number, then this over-rides + `iprint` (i.e., `iprint` gets the value of `disp`). + maxfun : int, optional + Maximum number of function evaluations. Note that this function + may violate the limit because of evaluating gradients by numerical + differentiation. + maxiter : int, optional + Maximum number of iterations. + callback : callable, optional + Called after each iteration, as ``callback(xk)``, where ``xk`` is the + current parameter vector. + maxls : int, optional + Maximum number of line search steps (per iteration). Default is 20. + + Returns + ------- + x : array_like + Estimated position of the minimum. + f : float + Value of `func` at the minimum. + d : dict + Information dictionary. + + * d['warnflag'] is + + - 0 if converged, + - 1 if too many function evaluations or too many iterations, + - 2 if stopped for another reason, given in d['task'] + + * d['grad'] is the gradient at the minimum (should be 0 ish) + * d['funcalls'] is the number of function calls made. + * d['nit'] is the number of iterations. + + See also + -------- + minimize: Interface to minimization algorithms for multivariate + functions. See the 'L-BFGS-B' `method` in particular. Note that the + `ftol` option is made available via that interface, while `factr` is + provided via this interface, where `factr` is the factor multiplying + the default machine floating-point precision to arrive at `ftol`: + ``ftol = factr * numpy.finfo(float).eps``. + + Notes + ----- + License of L-BFGS-B (FORTRAN code): + + The version included here (in fortran code) is 3.0 + (released April 25, 2011). It was written by Ciyou Zhu, Richard Byrd, + and Jorge Nocedal . It carries the following + condition for use: + + This software is freely available, but we expect that all publications + describing work using this software, or all commercial products using it, + quote at least one of the references given below. This software is released + under the BSD License. + + References + ---------- + * R. H. Byrd, P. Lu and J. Nocedal. A Limited Memory Algorithm for Bound + Constrained Optimization, (1995), SIAM Journal on Scientific and + Statistical Computing, 16, 5, pp. 1190-1208. + * C. Zhu, R. H. Byrd and J. Nocedal. L-BFGS-B: Algorithm 778: L-BFGS-B, + FORTRAN routines for large scale bound constrained optimization (1997), + ACM Transactions on Mathematical Software, 23, 4, pp. 550 - 560. + * J.L. Morales and J. Nocedal. L-BFGS-B: Remark on Algorithm 778: L-BFGS-B, + FORTRAN routines for large scale bound constrained optimization (2011), + ACM Transactions on Mathematical Software, 38, 1. + + Examples + -------- + Solve a linear regression problem via `fmin_l_bfgs_b`. To do this, first we define + an objective function ``f(m, b) = (y - y_model)**2``, where `y` describes the + observations and `y_model` the prediction of the linear model as + ``y_model = m*x + b``. The bounds for the parameters, ``m`` and ``b``, are arbitrarily + chosen as ``(0,5)`` and ``(5,10)`` for this example. + + >>> import numpy as np + >>> from scipy.optimize import fmin_l_bfgs_b + >>> X = np.arange(0, 10, 1) + >>> M = 2 + >>> B = 3 + >>> Y = M * X + B + >>> def func(parameters, *args): + ... x = args[0] + ... y = args[1] + ... m, b = parameters + ... y_model = m*x + b + ... error = sum(np.power((y - y_model), 2)) + ... return error + + >>> initial_values = np.array([0.0, 1.0]) + + >>> x_opt, f_opt, info = fmin_l_bfgs_b(func, x0=initial_values, args=(X, Y), + ... approx_grad=True) + >>> x_opt, f_opt + array([1.99999999, 3.00000006]), 1.7746231151323805e-14 # may vary + + The optimized parameters in ``x_opt`` agree with the ground truth parameters + ``m`` and ``b``. Next, let us perform a bound contrained optimization using the `bounds` + parameter. + + >>> bounds = [(0, 5), (5, 10)] + >>> x_opt, f_op, info = fmin_l_bfgs_b(func, x0=initial_values, args=(X, Y), + ... approx_grad=True, bounds=bounds) + >>> x_opt, f_opt + array([1.65990508, 5.31649385]), 15.721334516453945 # may vary + """ + # handle fprime/approx_grad + if approx_grad: + fun = func + jac = None + elif fprime is None: + fun = MemoizeJac(func) + jac = fun.derivative + else: + fun = func + jac = fprime + + # build options + callback = _wrap_callback(callback) + opts = {'disp': disp, + 'iprint': iprint, + 'maxcor': m, + 'ftol': factr * np.finfo(float).eps, + 'gtol': pgtol, + 'eps': epsilon, + 'maxfun': maxfun, + 'maxiter': maxiter, + 'callback': callback, + 'maxls': maxls} + + res = _minimize_lbfgsb(fun, x0, args=args, jac=jac, bounds=bounds, + **opts) + d = {'grad': res['jac'], + 'task': res['message'], + 'funcalls': res['nfev'], + 'nit': res['nit'], + 'warnflag': res['status']} + f = res['fun'] + x = res['x'] + + return x, f, d + + +def _minimize_lbfgsb(fun, x0, args=(), jac=None, bounds=None, + disp=None, maxcor=10, ftol=2.2204460492503131e-09, + gtol=1e-5, eps=1e-8, maxfun=15000, maxiter=15000, + iprint=-1, callback=None, maxls=20, + finite_diff_rel_step=None, **unknown_options): + """ + Minimize a scalar function of one or more variables using the L-BFGS-B + algorithm. + + Options + ------- + disp : None or int + If `disp is None` (the default), then the supplied version of `iprint` + is used. If `disp is not None`, then it overrides the supplied version + of `iprint` with the behaviour you outlined. + maxcor : int + The maximum number of variable metric corrections used to + define the limited memory matrix. (The limited memory BFGS + method does not store the full hessian but uses this many terms + in an approximation to it.) + ftol : float + The iteration stops when ``(f^k - + f^{k+1})/max{|f^k|,|f^{k+1}|,1} <= ftol``. + gtol : float + The iteration will stop when ``max{|proj g_i | i = 1, ..., n} + <= gtol`` where ``proj g_i`` is the i-th component of the + projected gradient. + eps : float or ndarray + If `jac is None` the absolute step size used for numerical + approximation of the jacobian via forward differences. + maxfun : int + Maximum number of function evaluations. Note that this function + may violate the limit because of evaluating gradients by numerical + differentiation. + maxiter : int + Maximum number of iterations. + iprint : int, optional + Controls the frequency of output. ``iprint < 0`` means no output; + ``iprint = 0`` print only one line at the last iteration; + ``0 < iprint < 99`` print also f and ``|proj g|`` every iprint iterations; + ``iprint = 99`` print details of every iteration except n-vectors; + ``iprint = 100`` print also the changes of active set and final x; + ``iprint > 100`` print details of every iteration including x and g. + maxls : int, optional + Maximum number of line search steps (per iteration). Default is 20. + finite_diff_rel_step : None or array_like, optional + If `jac in ['2-point', '3-point', 'cs']` the relative step size to + use for numerical approximation of the jacobian. The absolute step + size is computed as ``h = rel_step * sign(x) * max(1, abs(x))``, + possibly adjusted to fit into the bounds. For ``method='3-point'`` + the sign of `h` is ignored. If None (default) then step is selected + automatically. + + Notes + ----- + The option `ftol` is exposed via the `scipy.optimize.minimize` interface, + but calling `scipy.optimize.fmin_l_bfgs_b` directly exposes `factr`. The + relationship between the two is ``ftol = factr * numpy.finfo(float).eps``. + I.e., `factr` multiplies the default machine floating-point precision to + arrive at `ftol`. + + """ + _check_unknown_options(unknown_options) + m = maxcor + pgtol = gtol + factr = ftol / np.finfo(float).eps + + x0 = asarray(x0).ravel() + n, = x0.shape + + # historically old-style bounds were/are expected by lbfgsb. + # That's still the case but we'll deal with new-style from here on, + # it's easier + if bounds is None: + pass + elif len(bounds) != n: + raise ValueError('length of x0 != length of bounds') + else: + bounds = np.array(old_bound_to_new(bounds)) + + # check bounds + if (bounds[0] > bounds[1]).any(): + raise ValueError( + "LBFGSB - one of the lower bounds is greater than an upper bound." + ) + + # initial vector must lie within the bounds. Otherwise ScalarFunction and + # approx_derivative will cause problems + x0 = np.clip(x0, bounds[0], bounds[1]) + + if disp is not None: + if disp == 0: + iprint = -1 + else: + iprint = disp + + # _prepare_scalar_function can use bounds=None to represent no bounds + sf = _prepare_scalar_function(fun, x0, jac=jac, args=args, epsilon=eps, + bounds=bounds, + finite_diff_rel_step=finite_diff_rel_step) + + func_and_grad = sf.fun_and_grad + + fortran_int = _lbfgsb.types.intvar.dtype + + nbd = zeros(n, fortran_int) + low_bnd = zeros(n, float64) + upper_bnd = zeros(n, float64) + bounds_map = {(-np.inf, np.inf): 0, + (1, np.inf): 1, + (1, 1): 2, + (-np.inf, 1): 3} + + if bounds is not None: + for i in range(0, n): + l, u = bounds[0, i], bounds[1, i] + if not np.isinf(l): + low_bnd[i] = l + l = 1 + if not np.isinf(u): + upper_bnd[i] = u + u = 1 + nbd[i] = bounds_map[l, u] + + if not maxls > 0: + raise ValueError('maxls must be positive.') + + x = array(x0, float64) + f = array(0.0, float64) + g = zeros((n,), float64) + wa = zeros(2*m*n + 5*n + 11*m*m + 8*m, float64) + iwa = zeros(3*n, fortran_int) + task = zeros(1, 'S60') + csave = zeros(1, 'S60') + lsave = zeros(4, fortran_int) + isave = zeros(44, fortran_int) + dsave = zeros(29, float64) + + task[:] = 'START' + + n_iterations = 0 + + while 1: + # g may become float32 if a user provides a function that calculates + # the Jacobian in float32 (see gh-18730). The underlying Fortran code + # expects float64, so upcast it + g = g.astype(np.float64) + # x, f, g, wa, iwa, task, csave, lsave, isave, dsave = \ + _lbfgsb.setulb(m, x, low_bnd, upper_bnd, nbd, f, g, factr, + pgtol, wa, iwa, task, iprint, csave, lsave, + isave, dsave, maxls) + task_str = task.tobytes() + if task_str.startswith(b'FG'): + # The minimization routine wants f and g at the current x. + # Note that interruptions due to maxfun are postponed + # until the completion of the current minimization iteration. + # Overwrite f and g: + f, g = func_and_grad(x) + elif task_str.startswith(b'NEW_X'): + # new iteration + n_iterations += 1 + + intermediate_result = OptimizeResult(x=x, fun=f) + if _call_callback_maybe_halt(callback, intermediate_result): + task[:] = 'STOP: CALLBACK REQUESTED HALT' + if n_iterations >= maxiter: + task[:] = 'STOP: TOTAL NO. of ITERATIONS REACHED LIMIT' + elif sf.nfev > maxfun: + task[:] = ('STOP: TOTAL NO. of f AND g EVALUATIONS ' + 'EXCEEDS LIMIT') + else: + break + + task_str = task.tobytes().strip(b'\x00').strip() + if task_str.startswith(b'CONV'): + warnflag = 0 + elif sf.nfev > maxfun or n_iterations >= maxiter: + warnflag = 1 + else: + warnflag = 2 + + # These two portions of the workspace are described in the mainlb + # subroutine in lbfgsb.f. See line 363. + s = wa[0: m*n].reshape(m, n) + y = wa[m*n: 2*m*n].reshape(m, n) + + # See lbfgsb.f line 160 for this portion of the workspace. + # isave(31) = the total number of BFGS updates prior the current iteration; + n_bfgs_updates = isave[30] + + n_corrs = min(n_bfgs_updates, maxcor) + hess_inv = LbfgsInvHessProduct(s[:n_corrs], y[:n_corrs]) + + task_str = task_str.decode() + return OptimizeResult(fun=f, jac=g, nfev=sf.nfev, + njev=sf.ngev, + nit=n_iterations, status=warnflag, message=task_str, + x=x, success=(warnflag == 0), hess_inv=hess_inv) + + +class LbfgsInvHessProduct(LinearOperator): + """Linear operator for the L-BFGS approximate inverse Hessian. + + This operator computes the product of a vector with the approximate inverse + of the Hessian of the objective function, using the L-BFGS limited + memory approximation to the inverse Hessian, accumulated during the + optimization. + + Objects of this class implement the ``scipy.sparse.linalg.LinearOperator`` + interface. + + Parameters + ---------- + sk : array_like, shape=(n_corr, n) + Array of `n_corr` most recent updates to the solution vector. + (See [1]). + yk : array_like, shape=(n_corr, n) + Array of `n_corr` most recent updates to the gradient. (See [1]). + + References + ---------- + .. [1] Nocedal, Jorge. "Updating quasi-Newton matrices with limited + storage." Mathematics of computation 35.151 (1980): 773-782. + + """ + + def __init__(self, sk, yk): + """Construct the operator.""" + if sk.shape != yk.shape or sk.ndim != 2: + raise ValueError('sk and yk must have matching shape, (n_corrs, n)') + n_corrs, n = sk.shape + + super().__init__(dtype=np.float64, shape=(n, n)) + + self.sk = sk + self.yk = yk + self.n_corrs = n_corrs + self.rho = 1 / np.einsum('ij,ij->i', sk, yk) + + def _matvec(self, x): + """Efficient matrix-vector multiply with the BFGS matrices. + + This calculation is described in Section (4) of [1]. + + Parameters + ---------- + x : ndarray + An array with shape (n,) or (n,1). + + Returns + ------- + y : ndarray + The matrix-vector product + + """ + s, y, n_corrs, rho = self.sk, self.yk, self.n_corrs, self.rho + q = np.array(x, dtype=self.dtype, copy=True) + if q.ndim == 2 and q.shape[1] == 1: + q = q.reshape(-1) + + alpha = np.empty(n_corrs) + + for i in range(n_corrs-1, -1, -1): + alpha[i] = rho[i] * np.dot(s[i], q) + q = q - alpha[i]*y[i] + + r = q + for i in range(n_corrs): + beta = rho[i] * np.dot(y[i], r) + r = r + s[i] * (alpha[i] - beta) + + return r + + def todense(self): + """Return a dense array representation of this operator. + + Returns + ------- + arr : ndarray, shape=(n, n) + An array with the same shape and containing + the same data represented by this `LinearOperator`. + + """ + s, y, n_corrs, rho = self.sk, self.yk, self.n_corrs, self.rho + I = np.eye(*self.shape, dtype=self.dtype) + Hk = I + + for i in range(n_corrs): + A1 = I - s[i][:, np.newaxis] * y[i][np.newaxis, :] * rho[i] + A2 = I - y[i][:, np.newaxis] * s[i][np.newaxis, :] * rho[i] + + Hk = np.dot(A1, np.dot(Hk, A2)) + (rho[i] * s[i][:, np.newaxis] * + s[i][np.newaxis, :]) + return Hk diff --git a/llava_next/lib/python3.10/site-packages/scipy/optimize/_linesearch.py b/llava_next/lib/python3.10/site-packages/scipy/optimize/_linesearch.py new file mode 100644 index 0000000000000000000000000000000000000000..39e0b3826d5f2cb6390e01cb0f8b2f63ee8cf77e --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/scipy/optimize/_linesearch.py @@ -0,0 +1,896 @@ +""" +Functions +--------- +.. autosummary:: + :toctree: generated/ + + line_search_armijo + line_search_wolfe1 + line_search_wolfe2 + scalar_search_wolfe1 + scalar_search_wolfe2 + +""" +from warnings import warn + +from ._dcsrch import DCSRCH +import numpy as np + +__all__ = ['LineSearchWarning', 'line_search_wolfe1', 'line_search_wolfe2', + 'scalar_search_wolfe1', 'scalar_search_wolfe2', + 'line_search_armijo'] + +class LineSearchWarning(RuntimeWarning): + pass + + +def _check_c1_c2(c1, c2): + if not (0 < c1 < c2 < 1): + raise ValueError("'c1' and 'c2' do not satisfy" + "'0 < c1 < c2 < 1'.") + + +#------------------------------------------------------------------------------ +# Minpack's Wolfe line and scalar searches +#------------------------------------------------------------------------------ + +def line_search_wolfe1(f, fprime, xk, pk, gfk=None, + old_fval=None, old_old_fval=None, + args=(), c1=1e-4, c2=0.9, amax=50, amin=1e-8, + xtol=1e-14): + """ + As `scalar_search_wolfe1` but do a line search to direction `pk` + + Parameters + ---------- + f : callable + Function `f(x)` + fprime : callable + Gradient of `f` + xk : array_like + Current point + pk : array_like + Search direction + gfk : array_like, optional + Gradient of `f` at point `xk` + old_fval : float, optional + Value of `f` at point `xk` + old_old_fval : float, optional + Value of `f` at point preceding `xk` + + The rest of the parameters are the same as for `scalar_search_wolfe1`. + + Returns + ------- + stp, f_count, g_count, fval, old_fval + As in `line_search_wolfe1` + gval : array + Gradient of `f` at the final point + + Notes + ----- + Parameters `c1` and `c2` must satisfy ``0 < c1 < c2 < 1``. + + """ + if gfk is None: + gfk = fprime(xk, *args) + + gval = [gfk] + gc = [0] + fc = [0] + + def phi(s): + fc[0] += 1 + return f(xk + s*pk, *args) + + def derphi(s): + gval[0] = fprime(xk + s*pk, *args) + gc[0] += 1 + return np.dot(gval[0], pk) + + derphi0 = np.dot(gfk, pk) + + stp, fval, old_fval = scalar_search_wolfe1( + phi, derphi, old_fval, old_old_fval, derphi0, + c1=c1, c2=c2, amax=amax, amin=amin, xtol=xtol) + + return stp, fc[0], gc[0], fval, old_fval, gval[0] + + +def scalar_search_wolfe1(phi, derphi, phi0=None, old_phi0=None, derphi0=None, + c1=1e-4, c2=0.9, + amax=50, amin=1e-8, xtol=1e-14): + """ + Scalar function search for alpha that satisfies strong Wolfe conditions + + alpha > 0 is assumed to be a descent direction. + + Parameters + ---------- + phi : callable phi(alpha) + Function at point `alpha` + derphi : callable phi'(alpha) + Objective function derivative. Returns a scalar. + phi0 : float, optional + Value of phi at 0 + old_phi0 : float, optional + Value of phi at previous point + derphi0 : float, optional + Value derphi at 0 + c1 : float, optional + Parameter for Armijo condition rule. + c2 : float, optional + Parameter for curvature condition rule. + amax, amin : float, optional + Maximum and minimum step size + xtol : float, optional + Relative tolerance for an acceptable step. + + Returns + ------- + alpha : float + Step size, or None if no suitable step was found + phi : float + Value of `phi` at the new point `alpha` + phi0 : float + Value of `phi` at `alpha=0` + + Notes + ----- + Uses routine DCSRCH from MINPACK. + + Parameters `c1` and `c2` must satisfy ``0 < c1 < c2 < 1`` as described in [1]_. + + References + ---------- + + .. [1] Nocedal, J., & Wright, S. J. (2006). Numerical optimization. + In Springer Series in Operations Research and Financial Engineering. + (Springer Series in Operations Research and Financial Engineering). + Springer Nature. + + """ + _check_c1_c2(c1, c2) + + if phi0 is None: + phi0 = phi(0.) + if derphi0 is None: + derphi0 = derphi(0.) + + if old_phi0 is not None and derphi0 != 0: + alpha1 = min(1.0, 1.01*2*(phi0 - old_phi0)/derphi0) + if alpha1 < 0: + alpha1 = 1.0 + else: + alpha1 = 1.0 + + maxiter = 100 + + dcsrch = DCSRCH(phi, derphi, c1, c2, xtol, amin, amax) + stp, phi1, phi0, task = dcsrch( + alpha1, phi0=phi0, derphi0=derphi0, maxiter=maxiter + ) + + return stp, phi1, phi0 + + +line_search = line_search_wolfe1 + + +#------------------------------------------------------------------------------ +# Pure-Python Wolfe line and scalar searches +#------------------------------------------------------------------------------ + +# Note: `line_search_wolfe2` is the public `scipy.optimize.line_search` + +def line_search_wolfe2(f, myfprime, xk, pk, gfk=None, old_fval=None, + old_old_fval=None, args=(), c1=1e-4, c2=0.9, amax=None, + extra_condition=None, maxiter=10): + """Find alpha that satisfies strong Wolfe conditions. + + Parameters + ---------- + f : callable f(x,*args) + Objective function. + myfprime : callable f'(x,*args) + Objective function gradient. + xk : ndarray + Starting point. + pk : ndarray + Search direction. The search direction must be a descent direction + for the algorithm to converge. + gfk : ndarray, optional + Gradient value for x=xk (xk being the current parameter + estimate). Will be recomputed if omitted. + old_fval : float, optional + Function value for x=xk. Will be recomputed if omitted. + old_old_fval : float, optional + Function value for the point preceding x=xk. + args : tuple, optional + Additional arguments passed to objective function. + c1 : float, optional + Parameter for Armijo condition rule. + c2 : float, optional + Parameter for curvature condition rule. + amax : float, optional + Maximum step size + extra_condition : callable, optional + A callable of the form ``extra_condition(alpha, x, f, g)`` + returning a boolean. Arguments are the proposed step ``alpha`` + and the corresponding ``x``, ``f`` and ``g`` values. The line search + accepts the value of ``alpha`` only if this + callable returns ``True``. If the callable returns ``False`` + for the step length, the algorithm will continue with + new iterates. The callable is only called for iterates + satisfying the strong Wolfe conditions. + maxiter : int, optional + Maximum number of iterations to perform. + + Returns + ------- + alpha : float or None + Alpha for which ``x_new = x0 + alpha * pk``, + or None if the line search algorithm did not converge. + fc : int + Number of function evaluations made. + gc : int + Number of gradient evaluations made. + new_fval : float or None + New function value ``f(x_new)=f(x0+alpha*pk)``, + or None if the line search algorithm did not converge. + old_fval : float + Old function value ``f(x0)``. + new_slope : float or None + The local slope along the search direction at the + new value ````, + or None if the line search algorithm did not converge. + + + Notes + ----- + Uses the line search algorithm to enforce strong Wolfe + conditions. See Wright and Nocedal, 'Numerical Optimization', + 1999, pp. 59-61. + + The search direction `pk` must be a descent direction (e.g. + ``-myfprime(xk)``) to find a step length that satisfies the strong Wolfe + conditions. If the search direction is not a descent direction (e.g. + ``myfprime(xk)``), then `alpha`, `new_fval`, and `new_slope` will be None. + + Examples + -------- + >>> import numpy as np + >>> from scipy.optimize import line_search + + A objective function and its gradient are defined. + + >>> def obj_func(x): + ... return (x[0])**2+(x[1])**2 + >>> def obj_grad(x): + ... return [2*x[0], 2*x[1]] + + We can find alpha that satisfies strong Wolfe conditions. + + >>> start_point = np.array([1.8, 1.7]) + >>> search_gradient = np.array([-1.0, -1.0]) + >>> line_search(obj_func, obj_grad, start_point, search_gradient) + (1.0, 2, 1, 1.1300000000000001, 6.13, [1.6, 1.4]) + + """ + fc = [0] + gc = [0] + gval = [None] + gval_alpha = [None] + + def phi(alpha): + fc[0] += 1 + return f(xk + alpha * pk, *args) + + fprime = myfprime + + def derphi(alpha): + gc[0] += 1 + gval[0] = fprime(xk + alpha * pk, *args) # store for later use + gval_alpha[0] = alpha + return np.dot(gval[0], pk) + + if gfk is None: + gfk = fprime(xk, *args) + derphi0 = np.dot(gfk, pk) + + if extra_condition is not None: + # Add the current gradient as argument, to avoid needless + # re-evaluation + def extra_condition2(alpha, phi): + if gval_alpha[0] != alpha: + derphi(alpha) + x = xk + alpha * pk + return extra_condition(alpha, x, phi, gval[0]) + else: + extra_condition2 = None + + alpha_star, phi_star, old_fval, derphi_star = scalar_search_wolfe2( + phi, derphi, old_fval, old_old_fval, derphi0, c1, c2, amax, + extra_condition2, maxiter=maxiter) + + if derphi_star is None: + warn('The line search algorithm did not converge', + LineSearchWarning, stacklevel=2) + else: + # derphi_star is a number (derphi) -- so use the most recently + # calculated gradient used in computing it derphi = gfk*pk + # this is the gradient at the next step no need to compute it + # again in the outer loop. + derphi_star = gval[0] + + return alpha_star, fc[0], gc[0], phi_star, old_fval, derphi_star + + +def scalar_search_wolfe2(phi, derphi, phi0=None, + old_phi0=None, derphi0=None, + c1=1e-4, c2=0.9, amax=None, + extra_condition=None, maxiter=10): + """Find alpha that satisfies strong Wolfe conditions. + + alpha > 0 is assumed to be a descent direction. + + Parameters + ---------- + phi : callable phi(alpha) + Objective scalar function. + derphi : callable phi'(alpha) + Objective function derivative. Returns a scalar. + phi0 : float, optional + Value of phi at 0. + old_phi0 : float, optional + Value of phi at previous point. + derphi0 : float, optional + Value of derphi at 0 + c1 : float, optional + Parameter for Armijo condition rule. + c2 : float, optional + Parameter for curvature condition rule. + amax : float, optional + Maximum step size. + extra_condition : callable, optional + A callable of the form ``extra_condition(alpha, phi_value)`` + returning a boolean. The line search accepts the value + of ``alpha`` only if this callable returns ``True``. + If the callable returns ``False`` for the step length, + the algorithm will continue with new iterates. + The callable is only called for iterates satisfying + the strong Wolfe conditions. + maxiter : int, optional + Maximum number of iterations to perform. + + Returns + ------- + alpha_star : float or None + Best alpha, or None if the line search algorithm did not converge. + phi_star : float + phi at alpha_star. + phi0 : float + phi at 0. + derphi_star : float or None + derphi at alpha_star, or None if the line search algorithm + did not converge. + + Notes + ----- + Uses the line search algorithm to enforce strong Wolfe + conditions. See Wright and Nocedal, 'Numerical Optimization', + 1999, pp. 59-61. + + """ + _check_c1_c2(c1, c2) + + if phi0 is None: + phi0 = phi(0.) + + if derphi0 is None: + derphi0 = derphi(0.) + + alpha0 = 0 + if old_phi0 is not None and derphi0 != 0: + alpha1 = min(1.0, 1.01*2*(phi0 - old_phi0)/derphi0) + else: + alpha1 = 1.0 + + if alpha1 < 0: + alpha1 = 1.0 + + if amax is not None: + alpha1 = min(alpha1, amax) + + phi_a1 = phi(alpha1) + #derphi_a1 = derphi(alpha1) evaluated below + + phi_a0 = phi0 + derphi_a0 = derphi0 + + if extra_condition is None: + def extra_condition(alpha, phi): + return True + + for i in range(maxiter): + if alpha1 == 0 or (amax is not None and alpha0 > amax): + # alpha1 == 0: This shouldn't happen. Perhaps the increment has + # slipped below machine precision? + alpha_star = None + phi_star = phi0 + phi0 = old_phi0 + derphi_star = None + + if alpha1 == 0: + msg = 'Rounding errors prevent the line search from converging' + else: + msg = "The line search algorithm could not find a solution " + \ + "less than or equal to amax: %s" % amax + + warn(msg, LineSearchWarning, stacklevel=2) + break + + not_first_iteration = i > 0 + if (phi_a1 > phi0 + c1 * alpha1 * derphi0) or \ + ((phi_a1 >= phi_a0) and not_first_iteration): + alpha_star, phi_star, derphi_star = \ + _zoom(alpha0, alpha1, phi_a0, + phi_a1, derphi_a0, phi, derphi, + phi0, derphi0, c1, c2, extra_condition) + break + + derphi_a1 = derphi(alpha1) + if (abs(derphi_a1) <= -c2*derphi0): + if extra_condition(alpha1, phi_a1): + alpha_star = alpha1 + phi_star = phi_a1 + derphi_star = derphi_a1 + break + + if (derphi_a1 >= 0): + alpha_star, phi_star, derphi_star = \ + _zoom(alpha1, alpha0, phi_a1, + phi_a0, derphi_a1, phi, derphi, + phi0, derphi0, c1, c2, extra_condition) + break + + alpha2 = 2 * alpha1 # increase by factor of two on each iteration + if amax is not None: + alpha2 = min(alpha2, amax) + alpha0 = alpha1 + alpha1 = alpha2 + phi_a0 = phi_a1 + phi_a1 = phi(alpha1) + derphi_a0 = derphi_a1 + + else: + # stopping test maxiter reached + alpha_star = alpha1 + phi_star = phi_a1 + derphi_star = None + warn('The line search algorithm did not converge', + LineSearchWarning, stacklevel=2) + + return alpha_star, phi_star, phi0, derphi_star + + +def _cubicmin(a, fa, fpa, b, fb, c, fc): + """ + Finds the minimizer for a cubic polynomial that goes through the + points (a,fa), (b,fb), and (c,fc) with derivative at a of fpa. + + If no minimizer can be found, return None. + + """ + # f(x) = A *(x-a)^3 + B*(x-a)^2 + C*(x-a) + D + + with np.errstate(divide='raise', over='raise', invalid='raise'): + try: + C = fpa + db = b - a + dc = c - a + denom = (db * dc) ** 2 * (db - dc) + d1 = np.empty((2, 2)) + d1[0, 0] = dc ** 2 + d1[0, 1] = -db ** 2 + d1[1, 0] = -dc ** 3 + d1[1, 1] = db ** 3 + [A, B] = np.dot(d1, np.asarray([fb - fa - C * db, + fc - fa - C * dc]).flatten()) + A /= denom + B /= denom + radical = B * B - 3 * A * C + xmin = a + (-B + np.sqrt(radical)) / (3 * A) + except ArithmeticError: + return None + if not np.isfinite(xmin): + return None + return xmin + + +def _quadmin(a, fa, fpa, b, fb): + """ + Finds the minimizer for a quadratic polynomial that goes through + the points (a,fa), (b,fb) with derivative at a of fpa. + + """ + # f(x) = B*(x-a)^2 + C*(x-a) + D + with np.errstate(divide='raise', over='raise', invalid='raise'): + try: + D = fa + C = fpa + db = b - a * 1.0 + B = (fb - D - C * db) / (db * db) + xmin = a - C / (2.0 * B) + except ArithmeticError: + return None + if not np.isfinite(xmin): + return None + return xmin + + +def _zoom(a_lo, a_hi, phi_lo, phi_hi, derphi_lo, + phi, derphi, phi0, derphi0, c1, c2, extra_condition): + """Zoom stage of approximate linesearch satisfying strong Wolfe conditions. + + Part of the optimization algorithm in `scalar_search_wolfe2`. + + Notes + ----- + Implements Algorithm 3.6 (zoom) in Wright and Nocedal, + 'Numerical Optimization', 1999, pp. 61. + + """ + + maxiter = 10 + i = 0 + delta1 = 0.2 # cubic interpolant check + delta2 = 0.1 # quadratic interpolant check + phi_rec = phi0 + a_rec = 0 + while True: + # interpolate to find a trial step length between a_lo and + # a_hi Need to choose interpolation here. Use cubic + # interpolation and then if the result is within delta * + # dalpha or outside of the interval bounded by a_lo or a_hi + # then use quadratic interpolation, if the result is still too + # close, then use bisection + + dalpha = a_hi - a_lo + if dalpha < 0: + a, b = a_hi, a_lo + else: + a, b = a_lo, a_hi + + # minimizer of cubic interpolant + # (uses phi_lo, derphi_lo, phi_hi, and the most recent value of phi) + # + # if the result is too close to the end points (or out of the + # interval), then use quadratic interpolation with phi_lo, + # derphi_lo and phi_hi if the result is still too close to the + # end points (or out of the interval) then use bisection + + if (i > 0): + cchk = delta1 * dalpha + a_j = _cubicmin(a_lo, phi_lo, derphi_lo, a_hi, phi_hi, + a_rec, phi_rec) + if (i == 0) or (a_j is None) or (a_j > b - cchk) or (a_j < a + cchk): + qchk = delta2 * dalpha + a_j = _quadmin(a_lo, phi_lo, derphi_lo, a_hi, phi_hi) + if (a_j is None) or (a_j > b-qchk) or (a_j < a+qchk): + a_j = a_lo + 0.5*dalpha + + # Check new value of a_j + + phi_aj = phi(a_j) + if (phi_aj > phi0 + c1*a_j*derphi0) or (phi_aj >= phi_lo): + phi_rec = phi_hi + a_rec = a_hi + a_hi = a_j + phi_hi = phi_aj + else: + derphi_aj = derphi(a_j) + if abs(derphi_aj) <= -c2*derphi0 and extra_condition(a_j, phi_aj): + a_star = a_j + val_star = phi_aj + valprime_star = derphi_aj + break + if derphi_aj*(a_hi - a_lo) >= 0: + phi_rec = phi_hi + a_rec = a_hi + a_hi = a_lo + phi_hi = phi_lo + else: + phi_rec = phi_lo + a_rec = a_lo + a_lo = a_j + phi_lo = phi_aj + derphi_lo = derphi_aj + i += 1 + if (i > maxiter): + # Failed to find a conforming step size + a_star = None + val_star = None + valprime_star = None + break + return a_star, val_star, valprime_star + + +#------------------------------------------------------------------------------ +# Armijo line and scalar searches +#------------------------------------------------------------------------------ + +def line_search_armijo(f, xk, pk, gfk, old_fval, args=(), c1=1e-4, alpha0=1): + """Minimize over alpha, the function ``f(xk+alpha pk)``. + + Parameters + ---------- + f : callable + Function to be minimized. + xk : array_like + Current point. + pk : array_like + Search direction. + gfk : array_like + Gradient of `f` at point `xk`. + old_fval : float + Value of `f` at point `xk`. + args : tuple, optional + Optional arguments. + c1 : float, optional + Value to control stopping criterion. + alpha0 : scalar, optional + Value of `alpha` at start of the optimization. + + Returns + ------- + alpha + f_count + f_val_at_alpha + + Notes + ----- + Uses the interpolation algorithm (Armijo backtracking) as suggested by + Wright and Nocedal in 'Numerical Optimization', 1999, pp. 56-57 + + """ + xk = np.atleast_1d(xk) + fc = [0] + + def phi(alpha1): + fc[0] += 1 + return f(xk + alpha1*pk, *args) + + if old_fval is None: + phi0 = phi(0.) + else: + phi0 = old_fval # compute f(xk) -- done in past loop + + derphi0 = np.dot(gfk, pk) + alpha, phi1 = scalar_search_armijo(phi, phi0, derphi0, c1=c1, + alpha0=alpha0) + return alpha, fc[0], phi1 + + +def line_search_BFGS(f, xk, pk, gfk, old_fval, args=(), c1=1e-4, alpha0=1): + """ + Compatibility wrapper for `line_search_armijo` + """ + r = line_search_armijo(f, xk, pk, gfk, old_fval, args=args, c1=c1, + alpha0=alpha0) + return r[0], r[1], 0, r[2] + + +def scalar_search_armijo(phi, phi0, derphi0, c1=1e-4, alpha0=1, amin=0): + """Minimize over alpha, the function ``phi(alpha)``. + + Uses the interpolation algorithm (Armijo backtracking) as suggested by + Wright and Nocedal in 'Numerical Optimization', 1999, pp. 56-57 + + alpha > 0 is assumed to be a descent direction. + + Returns + ------- + alpha + phi1 + + """ + phi_a0 = phi(alpha0) + if phi_a0 <= phi0 + c1*alpha0*derphi0: + return alpha0, phi_a0 + + # Otherwise, compute the minimizer of a quadratic interpolant: + + alpha1 = -(derphi0) * alpha0**2 / 2.0 / (phi_a0 - phi0 - derphi0 * alpha0) + phi_a1 = phi(alpha1) + + if (phi_a1 <= phi0 + c1*alpha1*derphi0): + return alpha1, phi_a1 + + # Otherwise, loop with cubic interpolation until we find an alpha which + # satisfies the first Wolfe condition (since we are backtracking, we will + # assume that the value of alpha is not too small and satisfies the second + # condition. + + while alpha1 > amin: # we are assuming alpha>0 is a descent direction + factor = alpha0**2 * alpha1**2 * (alpha1-alpha0) + a = alpha0**2 * (phi_a1 - phi0 - derphi0*alpha1) - \ + alpha1**2 * (phi_a0 - phi0 - derphi0*alpha0) + a = a / factor + b = -alpha0**3 * (phi_a1 - phi0 - derphi0*alpha1) + \ + alpha1**3 * (phi_a0 - phi0 - derphi0*alpha0) + b = b / factor + + alpha2 = (-b + np.sqrt(abs(b**2 - 3 * a * derphi0))) / (3.0*a) + phi_a2 = phi(alpha2) + + if (phi_a2 <= phi0 + c1*alpha2*derphi0): + return alpha2, phi_a2 + + if (alpha1 - alpha2) > alpha1 / 2.0 or (1 - alpha2/alpha1) < 0.96: + alpha2 = alpha1 / 2.0 + + alpha0 = alpha1 + alpha1 = alpha2 + phi_a0 = phi_a1 + phi_a1 = phi_a2 + + # Failed to find a suitable step length + return None, phi_a1 + + +#------------------------------------------------------------------------------ +# Non-monotone line search for DF-SANE +#------------------------------------------------------------------------------ + +def _nonmonotone_line_search_cruz(f, x_k, d, prev_fs, eta, + gamma=1e-4, tau_min=0.1, tau_max=0.5): + """ + Nonmonotone backtracking line search as described in [1]_ + + Parameters + ---------- + f : callable + Function returning a tuple ``(f, F)`` where ``f`` is the value + of a merit function and ``F`` the residual. + x_k : ndarray + Initial position. + d : ndarray + Search direction. + prev_fs : float + List of previous merit function values. Should have ``len(prev_fs) <= M`` + where ``M`` is the nonmonotonicity window parameter. + eta : float + Allowed merit function increase, see [1]_ + gamma, tau_min, tau_max : float, optional + Search parameters, see [1]_ + + Returns + ------- + alpha : float + Step length + xp : ndarray + Next position + fp : float + Merit function value at next position + Fp : ndarray + Residual at next position + + References + ---------- + [1] "Spectral residual method without gradient information for solving + large-scale nonlinear systems of equations." W. La Cruz, + J.M. Martinez, M. Raydan. Math. Comp. **75**, 1429 (2006). + + """ + f_k = prev_fs[-1] + f_bar = max(prev_fs) + + alpha_p = 1 + alpha_m = 1 + alpha = 1 + + while True: + xp = x_k + alpha_p * d + fp, Fp = f(xp) + + if fp <= f_bar + eta - gamma * alpha_p**2 * f_k: + alpha = alpha_p + break + + alpha_tp = alpha_p**2 * f_k / (fp + (2*alpha_p - 1)*f_k) + + xp = x_k - alpha_m * d + fp, Fp = f(xp) + + if fp <= f_bar + eta - gamma * alpha_m**2 * f_k: + alpha = -alpha_m + break + + alpha_tm = alpha_m**2 * f_k / (fp + (2*alpha_m - 1)*f_k) + + alpha_p = np.clip(alpha_tp, tau_min * alpha_p, tau_max * alpha_p) + alpha_m = np.clip(alpha_tm, tau_min * alpha_m, tau_max * alpha_m) + + return alpha, xp, fp, Fp + + +def _nonmonotone_line_search_cheng(f, x_k, d, f_k, C, Q, eta, + gamma=1e-4, tau_min=0.1, tau_max=0.5, + nu=0.85): + """ + Nonmonotone line search from [1] + + Parameters + ---------- + f : callable + Function returning a tuple ``(f, F)`` where ``f`` is the value + of a merit function and ``F`` the residual. + x_k : ndarray + Initial position. + d : ndarray + Search direction. + f_k : float + Initial merit function value. + C, Q : float + Control parameters. On the first iteration, give values + Q=1.0, C=f_k + eta : float + Allowed merit function increase, see [1]_ + nu, gamma, tau_min, tau_max : float, optional + Search parameters, see [1]_ + + Returns + ------- + alpha : float + Step length + xp : ndarray + Next position + fp : float + Merit function value at next position + Fp : ndarray + Residual at next position + C : float + New value for the control parameter C + Q : float + New value for the control parameter Q + + References + ---------- + .. [1] W. Cheng & D.-H. Li, ''A derivative-free nonmonotone line + search and its application to the spectral residual + method'', IMA J. Numer. Anal. 29, 814 (2009). + + """ + alpha_p = 1 + alpha_m = 1 + alpha = 1 + + while True: + xp = x_k + alpha_p * d + fp, Fp = f(xp) + + if fp <= C + eta - gamma * alpha_p**2 * f_k: + alpha = alpha_p + break + + alpha_tp = alpha_p**2 * f_k / (fp + (2*alpha_p - 1)*f_k) + + xp = x_k - alpha_m * d + fp, Fp = f(xp) + + if fp <= C + eta - gamma * alpha_m**2 * f_k: + alpha = -alpha_m + break + + alpha_tm = alpha_m**2 * f_k / (fp + (2*alpha_m - 1)*f_k) + + alpha_p = np.clip(alpha_tp, tau_min * alpha_p, tau_max * alpha_p) + alpha_m = np.clip(alpha_tm, tau_min * alpha_m, tau_max * alpha_m) + + # Update C and Q + Q_next = nu * Q + 1 + C = (nu * Q * (C + eta) + fp) / Q_next + Q = Q_next + + return alpha, xp, fp, Fp, C, Q diff --git a/llava_next/lib/python3.10/site-packages/scipy/optimize/_linprog_doc.py b/llava_next/lib/python3.10/site-packages/scipy/optimize/_linprog_doc.py new file mode 100644 index 0000000000000000000000000000000000000000..56c914134bdef816c8eb00eb4ab011475cd5b4ea --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/scipy/optimize/_linprog_doc.py @@ -0,0 +1,1434 @@ +""" +Created on Sat Aug 22 19:49:17 2020 + +@author: matth +""" + + +def _linprog_highs_doc(c, A_ub=None, b_ub=None, A_eq=None, b_eq=None, + bounds=None, method='highs', callback=None, + maxiter=None, disp=False, presolve=True, + time_limit=None, + dual_feasibility_tolerance=None, + primal_feasibility_tolerance=None, + ipm_optimality_tolerance=None, + simplex_dual_edge_weight_strategy=None, + mip_rel_gap=None, + **unknown_options): + r""" + Linear programming: minimize a linear objective function subject to linear + equality and inequality constraints using one of the HiGHS solvers. + + Linear programming solves problems of the following form: + + .. math:: + + \min_x \ & c^T x \\ + \mbox{such that} \ & A_{ub} x \leq b_{ub},\\ + & A_{eq} x = b_{eq},\\ + & l \leq x \leq u , + + where :math:`x` is a vector of decision variables; :math:`c`, + :math:`b_{ub}`, :math:`b_{eq}`, :math:`l`, and :math:`u` are vectors; and + :math:`A_{ub}` and :math:`A_{eq}` are matrices. + + Alternatively, that's: + + minimize:: + + c @ x + + such that:: + + A_ub @ x <= b_ub + A_eq @ x == b_eq + lb <= x <= ub + + Note that by default ``lb = 0`` and ``ub = None`` unless specified with + ``bounds``. + + Parameters + ---------- + c : 1-D array + The coefficients of the linear objective function to be minimized. + A_ub : 2-D array, optional + The inequality constraint matrix. Each row of ``A_ub`` specifies the + coefficients of a linear inequality constraint on ``x``. + b_ub : 1-D array, optional + The inequality constraint vector. Each element represents an + upper bound on the corresponding value of ``A_ub @ x``. + A_eq : 2-D array, optional + The equality constraint matrix. Each row of ``A_eq`` specifies the + coefficients of a linear equality constraint on ``x``. + b_eq : 1-D array, optional + The equality constraint vector. Each element of ``A_eq @ x`` must equal + the corresponding element of ``b_eq``. + bounds : sequence, optional + A sequence of ``(min, max)`` pairs for each element in ``x``, defining + the minimum and maximum values of that decision variable. Use ``None`` + to indicate that there is no bound. By default, bounds are + ``(0, None)`` (all decision variables are non-negative). + If a single tuple ``(min, max)`` is provided, then ``min`` and + ``max`` will serve as bounds for all decision variables. + method : str + + This is the method-specific documentation for 'highs', which chooses + automatically between + :ref:`'highs-ds' ` and + :ref:`'highs-ipm' `. + :ref:`'interior-point' ` (default), + :ref:`'revised simplex' `, and + :ref:`'simplex' ` (legacy) + are also available. + integrality : 1-D array or int, optional + Indicates the type of integrality constraint on each decision variable. + + ``0`` : Continuous variable; no integrality constraint. + + ``1`` : Integer variable; decision variable must be an integer + within `bounds`. + + ``2`` : Semi-continuous variable; decision variable must be within + `bounds` or take value ``0``. + + ``3`` : Semi-integer variable; decision variable must be an integer + within `bounds` or take value ``0``. + + By default, all variables are continuous. + + For mixed integrality constraints, supply an array of shape `c.shape`. + To infer a constraint on each decision variable from shorter inputs, + the argument will be broadcasted to `c.shape` using `np.broadcast_to`. + + This argument is currently used only by the ``'highs'`` method and + ignored otherwise. + + Options + ------- + maxiter : int + The maximum number of iterations to perform in either phase. + For :ref:`'highs-ipm' `, this does not + include the number of crossover iterations. Default is the largest + possible value for an ``int`` on the platform. + disp : bool (default: ``False``) + Set to ``True`` if indicators of optimization status are to be + printed to the console during optimization. + presolve : bool (default: ``True``) + Presolve attempts to identify trivial infeasibilities, + identify trivial unboundedness, and simplify the problem before + sending it to the main solver. It is generally recommended + to keep the default setting ``True``; set to ``False`` if + presolve is to be disabled. + time_limit : float + The maximum time in seconds allotted to solve the problem; + default is the largest possible value for a ``double`` on the + platform. + dual_feasibility_tolerance : double (default: 1e-07) + Dual feasibility tolerance for + :ref:`'highs-ds' `. + The minimum of this and ``primal_feasibility_tolerance`` + is used for the feasibility tolerance of + :ref:`'highs-ipm' `. + primal_feasibility_tolerance : double (default: 1e-07) + Primal feasibility tolerance for + :ref:`'highs-ds' `. + The minimum of this and ``dual_feasibility_tolerance`` + is used for the feasibility tolerance of + :ref:`'highs-ipm' `. + ipm_optimality_tolerance : double (default: ``1e-08``) + Optimality tolerance for + :ref:`'highs-ipm' `. + Minimum allowable value is 1e-12. + simplex_dual_edge_weight_strategy : str (default: None) + Strategy for simplex dual edge weights. The default, ``None``, + automatically selects one of the following. + + ``'dantzig'`` uses Dantzig's original strategy of choosing the most + negative reduced cost. + + ``'devex'`` uses the strategy described in [15]_. + + ``steepest`` uses the exact steepest edge strategy as described in + [16]_. + + ``'steepest-devex'`` begins with the exact steepest edge strategy + until the computation is too costly or inexact and then switches to + the devex method. + + Currently, ``None`` always selects ``'steepest-devex'``, but this + may change as new options become available. + mip_rel_gap : double (default: None) + Termination criterion for MIP solver: solver will terminate when the + gap between the primal objective value and the dual objective bound, + scaled by the primal objective value, is <= mip_rel_gap. + unknown_options : dict + Optional arguments not used by this particular solver. If + ``unknown_options`` is non-empty, a warning is issued listing + all unused options. + + Returns + ------- + res : OptimizeResult + A :class:`scipy.optimize.OptimizeResult` consisting of the fields: + + x : 1D array + The values of the decision variables that minimizes the + objective function while satisfying the constraints. + fun : float + The optimal value of the objective function ``c @ x``. + slack : 1D array + The (nominally positive) values of the slack, + ``b_ub - A_ub @ x``. + con : 1D array + The (nominally zero) residuals of the equality constraints, + ``b_eq - A_eq @ x``. + success : bool + ``True`` when the algorithm succeeds in finding an optimal + solution. + status : int + An integer representing the exit status of the algorithm. + + ``0`` : Optimization terminated successfully. + + ``1`` : Iteration or time limit reached. + + ``2`` : Problem appears to be infeasible. + + ``3`` : Problem appears to be unbounded. + + ``4`` : The HiGHS solver ran into a problem. + + message : str + A string descriptor of the exit status of the algorithm. + nit : int + The total number of iterations performed. + For the HiGHS simplex method, this includes iterations in all + phases. For the HiGHS interior-point method, this does not include + crossover iterations. + crossover_nit : int + The number of primal/dual pushes performed during the + crossover routine for the HiGHS interior-point method. + This is ``0`` for the HiGHS simplex method. + ineqlin : OptimizeResult + Solution and sensitivity information corresponding to the + inequality constraints, `b_ub`. A dictionary consisting of the + fields: + + residual : np.ndnarray + The (nominally positive) values of the slack variables, + ``b_ub - A_ub @ x``. This quantity is also commonly + referred to as "slack". + + marginals : np.ndarray + The sensitivity (partial derivative) of the objective + function with respect to the right-hand side of the + inequality constraints, `b_ub`. + + eqlin : OptimizeResult + Solution and sensitivity information corresponding to the + equality constraints, `b_eq`. A dictionary consisting of the + fields: + + residual : np.ndarray + The (nominally zero) residuals of the equality constraints, + ``b_eq - A_eq @ x``. + + marginals : np.ndarray + The sensitivity (partial derivative) of the objective + function with respect to the right-hand side of the + equality constraints, `b_eq`. + + lower, upper : OptimizeResult + Solution and sensitivity information corresponding to the + lower and upper bounds on decision variables, `bounds`. + + residual : np.ndarray + The (nominally positive) values of the quantity + ``x - lb`` (lower) or ``ub - x`` (upper). + + marginals : np.ndarray + The sensitivity (partial derivative) of the objective + function with respect to the lower and upper + `bounds`. + + Notes + ----- + + Method :ref:`'highs-ds' ` is a wrapper + of the C++ high performance dual revised simplex implementation (HSOL) + [13]_, [14]_. Method :ref:`'highs-ipm' ` + is a wrapper of a C++ implementation of an **i**\ nterior-\ **p**\ oint + **m**\ ethod [13]_; it features a crossover routine, so it is as accurate + as a simplex solver. Method :ref:`'highs' ` chooses + between the two automatically. For new code involving `linprog`, we + recommend explicitly choosing one of these three method values instead of + :ref:`'interior-point' ` (default), + :ref:`'revised simplex' `, and + :ref:`'simplex' ` (legacy). + + The result fields `ineqlin`, `eqlin`, `lower`, and `upper` all contain + `marginals`, or partial derivatives of the objective function with respect + to the right-hand side of each constraint. These partial derivatives are + also referred to as "Lagrange multipliers", "dual values", and + "shadow prices". The sign convention of `marginals` is opposite that + of Lagrange multipliers produced by many nonlinear solvers. + + References + ---------- + .. [13] Huangfu, Q., Galabova, I., Feldmeier, M., and Hall, J. A. J. + "HiGHS - high performance software for linear optimization." + https://highs.dev/ + .. [14] Huangfu, Q. and Hall, J. A. J. "Parallelizing the dual revised + simplex method." Mathematical Programming Computation, 10 (1), + 119-142, 2018. DOI: 10.1007/s12532-017-0130-5 + .. [15] Harris, Paula MJ. "Pivot selection methods of the Devex LP code." + Mathematical programming 5.1 (1973): 1-28. + .. [16] Goldfarb, Donald, and John Ker Reid. "A practicable steepest-edge + simplex algorithm." Mathematical Programming 12.1 (1977): 361-371. + """ + pass + + +def _linprog_highs_ds_doc(c, A_ub=None, b_ub=None, A_eq=None, b_eq=None, + bounds=None, method='highs-ds', callback=None, + maxiter=None, disp=False, presolve=True, + time_limit=None, + dual_feasibility_tolerance=None, + primal_feasibility_tolerance=None, + simplex_dual_edge_weight_strategy=None, + **unknown_options): + r""" + Linear programming: minimize a linear objective function subject to linear + equality and inequality constraints using the HiGHS dual simplex solver. + + Linear programming solves problems of the following form: + + .. math:: + + \min_x \ & c^T x \\ + \mbox{such that} \ & A_{ub} x \leq b_{ub},\\ + & A_{eq} x = b_{eq},\\ + & l \leq x \leq u , + + where :math:`x` is a vector of decision variables; :math:`c`, + :math:`b_{ub}`, :math:`b_{eq}`, :math:`l`, and :math:`u` are vectors; and + :math:`A_{ub}` and :math:`A_{eq}` are matrices. + + Alternatively, that's: + + minimize:: + + c @ x + + such that:: + + A_ub @ x <= b_ub + A_eq @ x == b_eq + lb <= x <= ub + + Note that by default ``lb = 0`` and ``ub = None`` unless specified with + ``bounds``. + + Parameters + ---------- + c : 1-D array + The coefficients of the linear objective function to be minimized. + A_ub : 2-D array, optional + The inequality constraint matrix. Each row of ``A_ub`` specifies the + coefficients of a linear inequality constraint on ``x``. + b_ub : 1-D array, optional + The inequality constraint vector. Each element represents an + upper bound on the corresponding value of ``A_ub @ x``. + A_eq : 2-D array, optional + The equality constraint matrix. Each row of ``A_eq`` specifies the + coefficients of a linear equality constraint on ``x``. + b_eq : 1-D array, optional + The equality constraint vector. Each element of ``A_eq @ x`` must equal + the corresponding element of ``b_eq``. + bounds : sequence, optional + A sequence of ``(min, max)`` pairs for each element in ``x``, defining + the minimum and maximum values of that decision variable. Use ``None`` + to indicate that there is no bound. By default, bounds are + ``(0, None)`` (all decision variables are non-negative). + If a single tuple ``(min, max)`` is provided, then ``min`` and + ``max`` will serve as bounds for all decision variables. + method : str + + This is the method-specific documentation for 'highs-ds'. + :ref:`'highs' `, + :ref:`'highs-ipm' `, + :ref:`'interior-point' ` (default), + :ref:`'revised simplex' `, and + :ref:`'simplex' ` (legacy) + are also available. + + Options + ------- + maxiter : int + The maximum number of iterations to perform in either phase. + Default is the largest possible value for an ``int`` on the platform. + disp : bool (default: ``False``) + Set to ``True`` if indicators of optimization status are to be + printed to the console during optimization. + presolve : bool (default: ``True``) + Presolve attempts to identify trivial infeasibilities, + identify trivial unboundedness, and simplify the problem before + sending it to the main solver. It is generally recommended + to keep the default setting ``True``; set to ``False`` if + presolve is to be disabled. + time_limit : float + The maximum time in seconds allotted to solve the problem; + default is the largest possible value for a ``double`` on the + platform. + dual_feasibility_tolerance : double (default: 1e-07) + Dual feasibility tolerance for + :ref:`'highs-ds' `. + primal_feasibility_tolerance : double (default: 1e-07) + Primal feasibility tolerance for + :ref:`'highs-ds' `. + simplex_dual_edge_weight_strategy : str (default: None) + Strategy for simplex dual edge weights. The default, ``None``, + automatically selects one of the following. + + ``'dantzig'`` uses Dantzig's original strategy of choosing the most + negative reduced cost. + + ``'devex'`` uses the strategy described in [15]_. + + ``steepest`` uses the exact steepest edge strategy as described in + [16]_. + + ``'steepest-devex'`` begins with the exact steepest edge strategy + until the computation is too costly or inexact and then switches to + the devex method. + + Currently, ``None`` always selects ``'steepest-devex'``, but this + may change as new options become available. + unknown_options : dict + Optional arguments not used by this particular solver. If + ``unknown_options`` is non-empty, a warning is issued listing + all unused options. + + Returns + ------- + res : OptimizeResult + A :class:`scipy.optimize.OptimizeResult` consisting of the fields: + + x : 1D array + The values of the decision variables that minimizes the + objective function while satisfying the constraints. + fun : float + The optimal value of the objective function ``c @ x``. + slack : 1D array + The (nominally positive) values of the slack, + ``b_ub - A_ub @ x``. + con : 1D array + The (nominally zero) residuals of the equality constraints, + ``b_eq - A_eq @ x``. + success : bool + ``True`` when the algorithm succeeds in finding an optimal + solution. + status : int + An integer representing the exit status of the algorithm. + + ``0`` : Optimization terminated successfully. + + ``1`` : Iteration or time limit reached. + + ``2`` : Problem appears to be infeasible. + + ``3`` : Problem appears to be unbounded. + + ``4`` : The HiGHS solver ran into a problem. + + message : str + A string descriptor of the exit status of the algorithm. + nit : int + The total number of iterations performed. This includes iterations + in all phases. + crossover_nit : int + This is always ``0`` for the HiGHS simplex method. + For the HiGHS interior-point method, this is the number of + primal/dual pushes performed during the crossover routine. + ineqlin : OptimizeResult + Solution and sensitivity information corresponding to the + inequality constraints, `b_ub`. A dictionary consisting of the + fields: + + residual : np.ndnarray + The (nominally positive) values of the slack variables, + ``b_ub - A_ub @ x``. This quantity is also commonly + referred to as "slack". + + marginals : np.ndarray + The sensitivity (partial derivative) of the objective + function with respect to the right-hand side of the + inequality constraints, `b_ub`. + + eqlin : OptimizeResult + Solution and sensitivity information corresponding to the + equality constraints, `b_eq`. A dictionary consisting of the + fields: + + residual : np.ndarray + The (nominally zero) residuals of the equality constraints, + ``b_eq - A_eq @ x``. + + marginals : np.ndarray + The sensitivity (partial derivative) of the objective + function with respect to the right-hand side of the + equality constraints, `b_eq`. + + lower, upper : OptimizeResult + Solution and sensitivity information corresponding to the + lower and upper bounds on decision variables, `bounds`. + + residual : np.ndarray + The (nominally positive) values of the quantity + ``x - lb`` (lower) or ``ub - x`` (upper). + + marginals : np.ndarray + The sensitivity (partial derivative) of the objective + function with respect to the lower and upper + `bounds`. + + Notes + ----- + + Method :ref:`'highs-ds' ` is a wrapper + of the C++ high performance dual revised simplex implementation (HSOL) + [13]_, [14]_. Method :ref:`'highs-ipm' ` + is a wrapper of a C++ implementation of an **i**\ nterior-\ **p**\ oint + **m**\ ethod [13]_; it features a crossover routine, so it is as accurate + as a simplex solver. Method :ref:`'highs' ` chooses + between the two automatically. For new code involving `linprog`, we + recommend explicitly choosing one of these three method values instead of + :ref:`'interior-point' ` (default), + :ref:`'revised simplex' `, and + :ref:`'simplex' ` (legacy). + + The result fields `ineqlin`, `eqlin`, `lower`, and `upper` all contain + `marginals`, or partial derivatives of the objective function with respect + to the right-hand side of each constraint. These partial derivatives are + also referred to as "Lagrange multipliers", "dual values", and + "shadow prices". The sign convention of `marginals` is opposite that + of Lagrange multipliers produced by many nonlinear solvers. + + References + ---------- + .. [13] Huangfu, Q., Galabova, I., Feldmeier, M., and Hall, J. A. J. + "HiGHS - high performance software for linear optimization." + https://highs.dev/ + .. [14] Huangfu, Q. and Hall, J. A. J. "Parallelizing the dual revised + simplex method." Mathematical Programming Computation, 10 (1), + 119-142, 2018. DOI: 10.1007/s12532-017-0130-5 + .. [15] Harris, Paula MJ. "Pivot selection methods of the Devex LP code." + Mathematical programming 5.1 (1973): 1-28. + .. [16] Goldfarb, Donald, and John Ker Reid. "A practicable steepest-edge + simplex algorithm." Mathematical Programming 12.1 (1977): 361-371. + """ + pass + + +def _linprog_highs_ipm_doc(c, A_ub=None, b_ub=None, A_eq=None, b_eq=None, + bounds=None, method='highs-ipm', callback=None, + maxiter=None, disp=False, presolve=True, + time_limit=None, + dual_feasibility_tolerance=None, + primal_feasibility_tolerance=None, + ipm_optimality_tolerance=None, + **unknown_options): + r""" + Linear programming: minimize a linear objective function subject to linear + equality and inequality constraints using the HiGHS interior point solver. + + Linear programming solves problems of the following form: + + .. math:: + + \min_x \ & c^T x \\ + \mbox{such that} \ & A_{ub} x \leq b_{ub},\\ + & A_{eq} x = b_{eq},\\ + & l \leq x \leq u , + + where :math:`x` is a vector of decision variables; :math:`c`, + :math:`b_{ub}`, :math:`b_{eq}`, :math:`l`, and :math:`u` are vectors; and + :math:`A_{ub}` and :math:`A_{eq}` are matrices. + + Alternatively, that's: + + minimize:: + + c @ x + + such that:: + + A_ub @ x <= b_ub + A_eq @ x == b_eq + lb <= x <= ub + + Note that by default ``lb = 0`` and ``ub = None`` unless specified with + ``bounds``. + + Parameters + ---------- + c : 1-D array + The coefficients of the linear objective function to be minimized. + A_ub : 2-D array, optional + The inequality constraint matrix. Each row of ``A_ub`` specifies the + coefficients of a linear inequality constraint on ``x``. + b_ub : 1-D array, optional + The inequality constraint vector. Each element represents an + upper bound on the corresponding value of ``A_ub @ x``. + A_eq : 2-D array, optional + The equality constraint matrix. Each row of ``A_eq`` specifies the + coefficients of a linear equality constraint on ``x``. + b_eq : 1-D array, optional + The equality constraint vector. Each element of ``A_eq @ x`` must equal + the corresponding element of ``b_eq``. + bounds : sequence, optional + A sequence of ``(min, max)`` pairs for each element in ``x``, defining + the minimum and maximum values of that decision variable. Use ``None`` + to indicate that there is no bound. By default, bounds are + ``(0, None)`` (all decision variables are non-negative). + If a single tuple ``(min, max)`` is provided, then ``min`` and + ``max`` will serve as bounds for all decision variables. + method : str + + This is the method-specific documentation for 'highs-ipm'. + :ref:`'highs-ipm' `, + :ref:`'highs-ds' `, + :ref:`'interior-point' ` (default), + :ref:`'revised simplex' `, and + :ref:`'simplex' ` (legacy) + are also available. + + Options + ------- + maxiter : int + The maximum number of iterations to perform in either phase. + For :ref:`'highs-ipm' `, this does not + include the number of crossover iterations. Default is the largest + possible value for an ``int`` on the platform. + disp : bool (default: ``False``) + Set to ``True`` if indicators of optimization status are to be + printed to the console during optimization. + presolve : bool (default: ``True``) + Presolve attempts to identify trivial infeasibilities, + identify trivial unboundedness, and simplify the problem before + sending it to the main solver. It is generally recommended + to keep the default setting ``True``; set to ``False`` if + presolve is to be disabled. + time_limit : float + The maximum time in seconds allotted to solve the problem; + default is the largest possible value for a ``double`` on the + platform. + dual_feasibility_tolerance : double (default: 1e-07) + The minimum of this and ``primal_feasibility_tolerance`` + is used for the feasibility tolerance of + :ref:`'highs-ipm' `. + primal_feasibility_tolerance : double (default: 1e-07) + The minimum of this and ``dual_feasibility_tolerance`` + is used for the feasibility tolerance of + :ref:`'highs-ipm' `. + ipm_optimality_tolerance : double (default: ``1e-08``) + Optimality tolerance for + :ref:`'highs-ipm' `. + Minimum allowable value is 1e-12. + unknown_options : dict + Optional arguments not used by this particular solver. If + ``unknown_options`` is non-empty, a warning is issued listing + all unused options. + + Returns + ------- + res : OptimizeResult + A :class:`scipy.optimize.OptimizeResult` consisting of the fields: + + x : 1D array + The values of the decision variables that minimizes the + objective function while satisfying the constraints. + fun : float + The optimal value of the objective function ``c @ x``. + slack : 1D array + The (nominally positive) values of the slack, + ``b_ub - A_ub @ x``. + con : 1D array + The (nominally zero) residuals of the equality constraints, + ``b_eq - A_eq @ x``. + success : bool + ``True`` when the algorithm succeeds in finding an optimal + solution. + status : int + An integer representing the exit status of the algorithm. + + ``0`` : Optimization terminated successfully. + + ``1`` : Iteration or time limit reached. + + ``2`` : Problem appears to be infeasible. + + ``3`` : Problem appears to be unbounded. + + ``4`` : The HiGHS solver ran into a problem. + + message : str + A string descriptor of the exit status of the algorithm. + nit : int + The total number of iterations performed. + For the HiGHS interior-point method, this does not include + crossover iterations. + crossover_nit : int + The number of primal/dual pushes performed during the + crossover routine for the HiGHS interior-point method. + ineqlin : OptimizeResult + Solution and sensitivity information corresponding to the + inequality constraints, `b_ub`. A dictionary consisting of the + fields: + + residual : np.ndnarray + The (nominally positive) values of the slack variables, + ``b_ub - A_ub @ x``. This quantity is also commonly + referred to as "slack". + + marginals : np.ndarray + The sensitivity (partial derivative) of the objective + function with respect to the right-hand side of the + inequality constraints, `b_ub`. + + eqlin : OptimizeResult + Solution and sensitivity information corresponding to the + equality constraints, `b_eq`. A dictionary consisting of the + fields: + + residual : np.ndarray + The (nominally zero) residuals of the equality constraints, + ``b_eq - A_eq @ x``. + + marginals : np.ndarray + The sensitivity (partial derivative) of the objective + function with respect to the right-hand side of the + equality constraints, `b_eq`. + + lower, upper : OptimizeResult + Solution and sensitivity information corresponding to the + lower and upper bounds on decision variables, `bounds`. + + residual : np.ndarray + The (nominally positive) values of the quantity + ``x - lb`` (lower) or ``ub - x`` (upper). + + marginals : np.ndarray + The sensitivity (partial derivative) of the objective + function with respect to the lower and upper + `bounds`. + + Notes + ----- + + Method :ref:`'highs-ipm' ` + is a wrapper of a C++ implementation of an **i**\ nterior-\ **p**\ oint + **m**\ ethod [13]_; it features a crossover routine, so it is as accurate + as a simplex solver. + Method :ref:`'highs-ds' ` is a wrapper + of the C++ high performance dual revised simplex implementation (HSOL) + [13]_, [14]_. Method :ref:`'highs' ` chooses + between the two automatically. For new code involving `linprog`, we + recommend explicitly choosing one of these three method values instead of + :ref:`'interior-point' ` (default), + :ref:`'revised simplex' `, and + :ref:`'simplex' ` (legacy). + + The result fields `ineqlin`, `eqlin`, `lower`, and `upper` all contain + `marginals`, or partial derivatives of the objective function with respect + to the right-hand side of each constraint. These partial derivatives are + also referred to as "Lagrange multipliers", "dual values", and + "shadow prices". The sign convention of `marginals` is opposite that + of Lagrange multipliers produced by many nonlinear solvers. + + References + ---------- + .. [13] Huangfu, Q., Galabova, I., Feldmeier, M., and Hall, J. A. J. + "HiGHS - high performance software for linear optimization." + https://highs.dev/ + .. [14] Huangfu, Q. and Hall, J. A. J. "Parallelizing the dual revised + simplex method." Mathematical Programming Computation, 10 (1), + 119-142, 2018. DOI: 10.1007/s12532-017-0130-5 + """ + pass + + +def _linprog_ip_doc(c, A_ub=None, b_ub=None, A_eq=None, b_eq=None, + bounds=None, method='interior-point', callback=None, + maxiter=1000, disp=False, presolve=True, + tol=1e-8, autoscale=False, rr=True, + alpha0=.99995, beta=0.1, sparse=False, + lstsq=False, sym_pos=True, cholesky=True, pc=True, + ip=False, permc_spec='MMD_AT_PLUS_A', **unknown_options): + r""" + Linear programming: minimize a linear objective function subject to linear + equality and inequality constraints using the interior-point method of + [4]_. + + .. deprecated:: 1.9.0 + `method='interior-point'` will be removed in SciPy 1.11.0. + It is replaced by `method='highs'` because the latter is + faster and more robust. + + Linear programming solves problems of the following form: + + .. math:: + + \min_x \ & c^T x \\ + \mbox{such that} \ & A_{ub} x \leq b_{ub},\\ + & A_{eq} x = b_{eq},\\ + & l \leq x \leq u , + + where :math:`x` is a vector of decision variables; :math:`c`, + :math:`b_{ub}`, :math:`b_{eq}`, :math:`l`, and :math:`u` are vectors; and + :math:`A_{ub}` and :math:`A_{eq}` are matrices. + + Alternatively, that's: + + minimize:: + + c @ x + + such that:: + + A_ub @ x <= b_ub + A_eq @ x == b_eq + lb <= x <= ub + + Note that by default ``lb = 0`` and ``ub = None`` unless specified with + ``bounds``. + + Parameters + ---------- + c : 1-D array + The coefficients of the linear objective function to be minimized. + A_ub : 2-D array, optional + The inequality constraint matrix. Each row of ``A_ub`` specifies the + coefficients of a linear inequality constraint on ``x``. + b_ub : 1-D array, optional + The inequality constraint vector. Each element represents an + upper bound on the corresponding value of ``A_ub @ x``. + A_eq : 2-D array, optional + The equality constraint matrix. Each row of ``A_eq`` specifies the + coefficients of a linear equality constraint on ``x``. + b_eq : 1-D array, optional + The equality constraint vector. Each element of ``A_eq @ x`` must equal + the corresponding element of ``b_eq``. + bounds : sequence, optional + A sequence of ``(min, max)`` pairs for each element in ``x``, defining + the minimum and maximum values of that decision variable. Use ``None`` + to indicate that there is no bound. By default, bounds are + ``(0, None)`` (all decision variables are non-negative). + If a single tuple ``(min, max)`` is provided, then ``min`` and + ``max`` will serve as bounds for all decision variables. + method : str + This is the method-specific documentation for 'interior-point'. + :ref:`'highs' `, + :ref:`'highs-ds' `, + :ref:`'highs-ipm' `, + :ref:`'revised simplex' `, and + :ref:`'simplex' ` (legacy) + are also available. + callback : callable, optional + Callback function to be executed once per iteration. + + Options + ------- + maxiter : int (default: 1000) + The maximum number of iterations of the algorithm. + disp : bool (default: False) + Set to ``True`` if indicators of optimization status are to be printed + to the console each iteration. + presolve : bool (default: True) + Presolve attempts to identify trivial infeasibilities, + identify trivial unboundedness, and simplify the problem before + sending it to the main solver. It is generally recommended + to keep the default setting ``True``; set to ``False`` if + presolve is to be disabled. + tol : float (default: 1e-8) + Termination tolerance to be used for all termination criteria; + see [4]_ Section 4.5. + autoscale : bool (default: False) + Set to ``True`` to automatically perform equilibration. + Consider using this option if the numerical values in the + constraints are separated by several orders of magnitude. + rr : bool (default: True) + Set to ``False`` to disable automatic redundancy removal. + alpha0 : float (default: 0.99995) + The maximal step size for Mehrota's predictor-corrector search + direction; see :math:`\beta_{3}` of [4]_ Table 8.1. + beta : float (default: 0.1) + The desired reduction of the path parameter :math:`\mu` (see [6]_) + when Mehrota's predictor-corrector is not in use (uncommon). + sparse : bool (default: False) + Set to ``True`` if the problem is to be treated as sparse after + presolve. If either ``A_eq`` or ``A_ub`` is a sparse matrix, + this option will automatically be set ``True``, and the problem + will be treated as sparse even during presolve. If your constraint + matrices contain mostly zeros and the problem is not very small (less + than about 100 constraints or variables), consider setting ``True`` + or providing ``A_eq`` and ``A_ub`` as sparse matrices. + lstsq : bool (default: ``False``) + Set to ``True`` if the problem is expected to be very poorly + conditioned. This should always be left ``False`` unless severe + numerical difficulties are encountered. Leave this at the default + unless you receive a warning message suggesting otherwise. + sym_pos : bool (default: True) + Leave ``True`` if the problem is expected to yield a well conditioned + symmetric positive definite normal equation matrix + (almost always). Leave this at the default unless you receive + a warning message suggesting otherwise. + cholesky : bool (default: True) + Set to ``True`` if the normal equations are to be solved by explicit + Cholesky decomposition followed by explicit forward/backward + substitution. This is typically faster for problems + that are numerically well-behaved. + pc : bool (default: True) + Leave ``True`` if the predictor-corrector method of Mehrota is to be + used. This is almost always (if not always) beneficial. + ip : bool (default: False) + Set to ``True`` if the improved initial point suggestion due to [4]_ + Section 4.3 is desired. Whether this is beneficial or not + depends on the problem. + permc_spec : str (default: 'MMD_AT_PLUS_A') + (Has effect only with ``sparse = True``, ``lstsq = False``, ``sym_pos = + True``, and no SuiteSparse.) + A matrix is factorized in each iteration of the algorithm. + This option specifies how to permute the columns of the matrix for + sparsity preservation. Acceptable values are: + + - ``NATURAL``: natural ordering. + - ``MMD_ATA``: minimum degree ordering on the structure of A^T A. + - ``MMD_AT_PLUS_A``: minimum degree ordering on the structure of A^T+A. + - ``COLAMD``: approximate minimum degree column ordering. + + This option can impact the convergence of the + interior point algorithm; test different values to determine which + performs best for your problem. For more information, refer to + ``scipy.sparse.linalg.splu``. + unknown_options : dict + Optional arguments not used by this particular solver. If + `unknown_options` is non-empty a warning is issued listing all + unused options. + + Returns + ------- + res : OptimizeResult + A :class:`scipy.optimize.OptimizeResult` consisting of the fields: + + x : 1-D array + The values of the decision variables that minimizes the + objective function while satisfying the constraints. + fun : float + The optimal value of the objective function ``c @ x``. + slack : 1-D array + The (nominally positive) values of the slack variables, + ``b_ub - A_ub @ x``. + con : 1-D array + The (nominally zero) residuals of the equality constraints, + ``b_eq - A_eq @ x``. + success : bool + ``True`` when the algorithm succeeds in finding an optimal + solution. + status : int + An integer representing the exit status of the algorithm. + + ``0`` : Optimization terminated successfully. + + ``1`` : Iteration limit reached. + + ``2`` : Problem appears to be infeasible. + + ``3`` : Problem appears to be unbounded. + + ``4`` : Numerical difficulties encountered. + + message : str + A string descriptor of the exit status of the algorithm. + nit : int + The total number of iterations performed in all phases. + + + Notes + ----- + This method implements the algorithm outlined in [4]_ with ideas from [8]_ + and a structure inspired by the simpler methods of [6]_. + + The primal-dual path following method begins with initial 'guesses' of + the primal and dual variables of the standard form problem and iteratively + attempts to solve the (nonlinear) Karush-Kuhn-Tucker conditions for the + problem with a gradually reduced logarithmic barrier term added to the + objective. This particular implementation uses a homogeneous self-dual + formulation, which provides certificates of infeasibility or unboundedness + where applicable. + + The default initial point for the primal and dual variables is that + defined in [4]_ Section 4.4 Equation 8.22. Optionally (by setting initial + point option ``ip=True``), an alternate (potentially improved) starting + point can be calculated according to the additional recommendations of + [4]_ Section 4.4. + + A search direction is calculated using the predictor-corrector method + (single correction) proposed by Mehrota and detailed in [4]_ Section 4.1. + (A potential improvement would be to implement the method of multiple + corrections described in [4]_ Section 4.2.) In practice, this is + accomplished by solving the normal equations, [4]_ Section 5.1 Equations + 8.31 and 8.32, derived from the Newton equations [4]_ Section 5 Equations + 8.25 (compare to [4]_ Section 4 Equations 8.6-8.8). The advantage of + solving the normal equations rather than 8.25 directly is that the + matrices involved are symmetric positive definite, so Cholesky + decomposition can be used rather than the more expensive LU factorization. + + With default options, the solver used to perform the factorization depends + on third-party software availability and the conditioning of the problem. + + For dense problems, solvers are tried in the following order: + + 1. ``scipy.linalg.cho_factor`` + + 2. ``scipy.linalg.solve`` with option ``sym_pos=True`` + + 3. ``scipy.linalg.solve`` with option ``sym_pos=False`` + + 4. ``scipy.linalg.lstsq`` + + For sparse problems: + + 1. ``sksparse.cholmod.cholesky`` (if scikit-sparse and SuiteSparse are + installed) + + 2. ``scipy.sparse.linalg.factorized`` (if scikit-umfpack and SuiteSparse + are installed) + + 3. ``scipy.sparse.linalg.splu`` (which uses SuperLU distributed with SciPy) + + 4. ``scipy.sparse.linalg.lsqr`` + + If the solver fails for any reason, successively more robust (but slower) + solvers are attempted in the order indicated. Attempting, failing, and + re-starting factorization can be time consuming, so if the problem is + numerically challenging, options can be set to bypass solvers that are + failing. Setting ``cholesky=False`` skips to solver 2, + ``sym_pos=False`` skips to solver 3, and ``lstsq=True`` skips + to solver 4 for both sparse and dense problems. + + Potential improvements for combatting issues associated with dense + columns in otherwise sparse problems are outlined in [4]_ Section 5.3 and + [10]_ Section 4.1-4.2; the latter also discusses the alleviation of + accuracy issues associated with the substitution approach to free + variables. + + After calculating the search direction, the maximum possible step size + that does not activate the non-negativity constraints is calculated, and + the smaller of this step size and unity is applied (as in [4]_ Section + 4.1.) [4]_ Section 4.3 suggests improvements for choosing the step size. + + The new point is tested according to the termination conditions of [4]_ + Section 4.5. The same tolerance, which can be set using the ``tol`` option, + is used for all checks. (A potential improvement would be to expose + the different tolerances to be set independently.) If optimality, + unboundedness, or infeasibility is detected, the solve procedure + terminates; otherwise it repeats. + + Whereas the top level ``linprog`` module expects a problem of form: + + Minimize:: + + c @ x + + Subject to:: + + A_ub @ x <= b_ub + A_eq @ x == b_eq + lb <= x <= ub + + where ``lb = 0`` and ``ub = None`` unless set in ``bounds``. The problem + is automatically converted to the form: + + Minimize:: + + c @ x + + Subject to:: + + A @ x == b + x >= 0 + + for solution. That is, the original problem contains equality, upper-bound + and variable constraints whereas the method specific solver requires + equality constraints and variable non-negativity. ``linprog`` converts the + original problem to standard form by converting the simple bounds to upper + bound constraints, introducing non-negative slack variables for inequality + constraints, and expressing unbounded variables as the difference between + two non-negative variables. The problem is converted back to the original + form before results are reported. + + References + ---------- + .. [4] Andersen, Erling D., and Knud D. Andersen. "The MOSEK interior point + optimizer for linear programming: an implementation of the + homogeneous algorithm." High performance optimization. Springer US, + 2000. 197-232. + .. [6] Freund, Robert M. "Primal-Dual Interior-Point Methods for Linear + Programming based on Newton's Method." Unpublished Course Notes, + March 2004. Available 2/25/2017 at + https://ocw.mit.edu/courses/sloan-school-of-management/15-084j-nonlinear-programming-spring-2004/lecture-notes/lec14_int_pt_mthd.pdf + .. [8] Andersen, Erling D., and Knud D. Andersen. "Presolving in linear + programming." Mathematical Programming 71.2 (1995): 221-245. + .. [9] Bertsimas, Dimitris, and J. Tsitsiklis. "Introduction to linear + programming." Athena Scientific 1 (1997): 997. + .. [10] Andersen, Erling D., et al. Implementation of interior point + methods for large scale linear programming. HEC/Universite de + Geneve, 1996. + """ + pass + + +def _linprog_rs_doc(c, A_ub=None, b_ub=None, A_eq=None, b_eq=None, + bounds=None, method='interior-point', callback=None, + x0=None, maxiter=5000, disp=False, presolve=True, + tol=1e-12, autoscale=False, rr=True, maxupdate=10, + mast=False, pivot="mrc", **unknown_options): + r""" + Linear programming: minimize a linear objective function subject to linear + equality and inequality constraints using the revised simplex method. + + .. deprecated:: 1.9.0 + `method='revised simplex'` will be removed in SciPy 1.11.0. + It is replaced by `method='highs'` because the latter is + faster and more robust. + + Linear programming solves problems of the following form: + + .. math:: + + \min_x \ & c^T x \\ + \mbox{such that} \ & A_{ub} x \leq b_{ub},\\ + & A_{eq} x = b_{eq},\\ + & l \leq x \leq u , + + where :math:`x` is a vector of decision variables; :math:`c`, + :math:`b_{ub}`, :math:`b_{eq}`, :math:`l`, and :math:`u` are vectors; and + :math:`A_{ub}` and :math:`A_{eq}` are matrices. + + Alternatively, that's: + + minimize:: + + c @ x + + such that:: + + A_ub @ x <= b_ub + A_eq @ x == b_eq + lb <= x <= ub + + Note that by default ``lb = 0`` and ``ub = None`` unless specified with + ``bounds``. + + Parameters + ---------- + c : 1-D array + The coefficients of the linear objective function to be minimized. + A_ub : 2-D array, optional + The inequality constraint matrix. Each row of ``A_ub`` specifies the + coefficients of a linear inequality constraint on ``x``. + b_ub : 1-D array, optional + The inequality constraint vector. Each element represents an + upper bound on the corresponding value of ``A_ub @ x``. + A_eq : 2-D array, optional + The equality constraint matrix. Each row of ``A_eq`` specifies the + coefficients of a linear equality constraint on ``x``. + b_eq : 1-D array, optional + The equality constraint vector. Each element of ``A_eq @ x`` must equal + the corresponding element of ``b_eq``. + bounds : sequence, optional + A sequence of ``(min, max)`` pairs for each element in ``x``, defining + the minimum and maximum values of that decision variable. Use ``None`` + to indicate that there is no bound. By default, bounds are + ``(0, None)`` (all decision variables are non-negative). + If a single tuple ``(min, max)`` is provided, then ``min`` and + ``max`` will serve as bounds for all decision variables. + method : str + This is the method-specific documentation for 'revised simplex'. + :ref:`'highs' `, + :ref:`'highs-ds' `, + :ref:`'highs-ipm' `, + :ref:`'interior-point' ` (default), + and :ref:`'simplex' ` (legacy) + are also available. + callback : callable, optional + Callback function to be executed once per iteration. + x0 : 1-D array, optional + Guess values of the decision variables, which will be refined by + the optimization algorithm. This argument is currently used only by the + 'revised simplex' method, and can only be used if `x0` represents a + basic feasible solution. + + Options + ------- + maxiter : int (default: 5000) + The maximum number of iterations to perform in either phase. + disp : bool (default: False) + Set to ``True`` if indicators of optimization status are to be printed + to the console each iteration. + presolve : bool (default: True) + Presolve attempts to identify trivial infeasibilities, + identify trivial unboundedness, and simplify the problem before + sending it to the main solver. It is generally recommended + to keep the default setting ``True``; set to ``False`` if + presolve is to be disabled. + tol : float (default: 1e-12) + The tolerance which determines when a solution is "close enough" to + zero in Phase 1 to be considered a basic feasible solution or close + enough to positive to serve as an optimal solution. + autoscale : bool (default: False) + Set to ``True`` to automatically perform equilibration. + Consider using this option if the numerical values in the + constraints are separated by several orders of magnitude. + rr : bool (default: True) + Set to ``False`` to disable automatic redundancy removal. + maxupdate : int (default: 10) + The maximum number of updates performed on the LU factorization. + After this many updates is reached, the basis matrix is factorized + from scratch. + mast : bool (default: False) + Minimize Amortized Solve Time. If enabled, the average time to solve + a linear system using the basis factorization is measured. Typically, + the average solve time will decrease with each successive solve after + initial factorization, as factorization takes much more time than the + solve operation (and updates). Eventually, however, the updated + factorization becomes sufficiently complex that the average solve time + begins to increase. When this is detected, the basis is refactorized + from scratch. Enable this option to maximize speed at the risk of + nondeterministic behavior. Ignored if ``maxupdate`` is 0. + pivot : "mrc" or "bland" (default: "mrc") + Pivot rule: Minimum Reduced Cost ("mrc") or Bland's rule ("bland"). + Choose Bland's rule if iteration limit is reached and cycling is + suspected. + unknown_options : dict + Optional arguments not used by this particular solver. If + `unknown_options` is non-empty a warning is issued listing all + unused options. + + Returns + ------- + res : OptimizeResult + A :class:`scipy.optimize.OptimizeResult` consisting of the fields: + + x : 1-D array + The values of the decision variables that minimizes the + objective function while satisfying the constraints. + fun : float + The optimal value of the objective function ``c @ x``. + slack : 1-D array + The (nominally positive) values of the slack variables, + ``b_ub - A_ub @ x``. + con : 1-D array + The (nominally zero) residuals of the equality constraints, + ``b_eq - A_eq @ x``. + success : bool + ``True`` when the algorithm succeeds in finding an optimal + solution. + status : int + An integer representing the exit status of the algorithm. + + ``0`` : Optimization terminated successfully. + + ``1`` : Iteration limit reached. + + ``2`` : Problem appears to be infeasible. + + ``3`` : Problem appears to be unbounded. + + ``4`` : Numerical difficulties encountered. + + ``5`` : Problem has no constraints; turn presolve on. + + ``6`` : Invalid guess provided. + + message : str + A string descriptor of the exit status of the algorithm. + nit : int + The total number of iterations performed in all phases. + + + Notes + ----- + Method *revised simplex* uses the revised simplex method as described in + [9]_, except that a factorization [11]_ of the basis matrix, rather than + its inverse, is efficiently maintained and used to solve the linear systems + at each iteration of the algorithm. + + References + ---------- + .. [9] Bertsimas, Dimitris, and J. Tsitsiklis. "Introduction to linear + programming." Athena Scientific 1 (1997): 997. + .. [11] Bartels, Richard H. "A stabilization of the simplex method." + Journal in Numerische Mathematik 16.5 (1971): 414-434. + """ + pass + + +def _linprog_simplex_doc(c, A_ub=None, b_ub=None, A_eq=None, b_eq=None, + bounds=None, method='interior-point', callback=None, + maxiter=5000, disp=False, presolve=True, + tol=1e-12, autoscale=False, rr=True, bland=False, + **unknown_options): + r""" + Linear programming: minimize a linear objective function subject to linear + equality and inequality constraints using the tableau-based simplex method. + + .. deprecated:: 1.9.0 + `method='simplex'` will be removed in SciPy 1.11.0. + It is replaced by `method='highs'` because the latter is + faster and more robust. + + Linear programming solves problems of the following form: + + .. math:: + + \min_x \ & c^T x \\ + \mbox{such that} \ & A_{ub} x \leq b_{ub},\\ + & A_{eq} x = b_{eq},\\ + & l \leq x \leq u , + + where :math:`x` is a vector of decision variables; :math:`c`, + :math:`b_{ub}`, :math:`b_{eq}`, :math:`l`, and :math:`u` are vectors; and + :math:`A_{ub}` and :math:`A_{eq}` are matrices. + + Alternatively, that's: + + minimize:: + + c @ x + + such that:: + + A_ub @ x <= b_ub + A_eq @ x == b_eq + lb <= x <= ub + + Note that by default ``lb = 0`` and ``ub = None`` unless specified with + ``bounds``. + + Parameters + ---------- + c : 1-D array + The coefficients of the linear objective function to be minimized. + A_ub : 2-D array, optional + The inequality constraint matrix. Each row of ``A_ub`` specifies the + coefficients of a linear inequality constraint on ``x``. + b_ub : 1-D array, optional + The inequality constraint vector. Each element represents an + upper bound on the corresponding value of ``A_ub @ x``. + A_eq : 2-D array, optional + The equality constraint matrix. Each row of ``A_eq`` specifies the + coefficients of a linear equality constraint on ``x``. + b_eq : 1-D array, optional + The equality constraint vector. Each element of ``A_eq @ x`` must equal + the corresponding element of ``b_eq``. + bounds : sequence, optional + A sequence of ``(min, max)`` pairs for each element in ``x``, defining + the minimum and maximum values of that decision variable. Use ``None`` + to indicate that there is no bound. By default, bounds are + ``(0, None)`` (all decision variables are non-negative). + If a single tuple ``(min, max)`` is provided, then ``min`` and + ``max`` will serve as bounds for all decision variables. + method : str + This is the method-specific documentation for 'simplex'. + :ref:`'highs' `, + :ref:`'highs-ds' `, + :ref:`'highs-ipm' `, + :ref:`'interior-point' ` (default), + and :ref:`'revised simplex' ` + are also available. + callback : callable, optional + Callback function to be executed once per iteration. + + Options + ------- + maxiter : int (default: 5000) + The maximum number of iterations to perform in either phase. + disp : bool (default: False) + Set to ``True`` if indicators of optimization status are to be printed + to the console each iteration. + presolve : bool (default: True) + Presolve attempts to identify trivial infeasibilities, + identify trivial unboundedness, and simplify the problem before + sending it to the main solver. It is generally recommended + to keep the default setting ``True``; set to ``False`` if + presolve is to be disabled. + tol : float (default: 1e-12) + The tolerance which determines when a solution is "close enough" to + zero in Phase 1 to be considered a basic feasible solution or close + enough to positive to serve as an optimal solution. + autoscale : bool (default: False) + Set to ``True`` to automatically perform equilibration. + Consider using this option if the numerical values in the + constraints are separated by several orders of magnitude. + rr : bool (default: True) + Set to ``False`` to disable automatic redundancy removal. + bland : bool + If True, use Bland's anti-cycling rule [3]_ to choose pivots to + prevent cycling. If False, choose pivots which should lead to a + converged solution more quickly. The latter method is subject to + cycling (non-convergence) in rare instances. + unknown_options : dict + Optional arguments not used by this particular solver. If + `unknown_options` is non-empty a warning is issued listing all + unused options. + + Returns + ------- + res : OptimizeResult + A :class:`scipy.optimize.OptimizeResult` consisting of the fields: + + x : 1-D array + The values of the decision variables that minimizes the + objective function while satisfying the constraints. + fun : float + The optimal value of the objective function ``c @ x``. + slack : 1-D array + The (nominally positive) values of the slack variables, + ``b_ub - A_ub @ x``. + con : 1-D array + The (nominally zero) residuals of the equality constraints, + ``b_eq - A_eq @ x``. + success : bool + ``True`` when the algorithm succeeds in finding an optimal + solution. + status : int + An integer representing the exit status of the algorithm. + + ``0`` : Optimization terminated successfully. + + ``1`` : Iteration limit reached. + + ``2`` : Problem appears to be infeasible. + + ``3`` : Problem appears to be unbounded. + + ``4`` : Numerical difficulties encountered. + + message : str + A string descriptor of the exit status of the algorithm. + nit : int + The total number of iterations performed in all phases. + + References + ---------- + .. [1] Dantzig, George B., Linear programming and extensions. Rand + Corporation Research Study Princeton Univ. Press, Princeton, NJ, + 1963 + .. [2] Hillier, S.H. and Lieberman, G.J. (1995), "Introduction to + Mathematical Programming", McGraw-Hill, Chapter 4. + .. [3] Bland, Robert G. New finite pivoting rules for the simplex method. + Mathematics of Operations Research (2), 1977: pp. 103-107. + """ + pass diff --git a/llava_next/lib/python3.10/site-packages/scipy/optimize/_linprog_rs.py b/llava_next/lib/python3.10/site-packages/scipy/optimize/_linprog_rs.py new file mode 100644 index 0000000000000000000000000000000000000000..826ceffce398a6f58bdfcd6264e2f14fc5f6f8ee --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/scipy/optimize/_linprog_rs.py @@ -0,0 +1,572 @@ +"""Revised simplex method for linear programming + +The *revised simplex* method uses the method described in [1]_, except +that a factorization [2]_ of the basis matrix, rather than its inverse, +is efficiently maintained and used to solve the linear systems at each +iteration of the algorithm. + +.. versionadded:: 1.3.0 + +References +---------- +.. [1] Bertsimas, Dimitris, and J. Tsitsiklis. "Introduction to linear + programming." Athena Scientific 1 (1997): 997. +.. [2] Bartels, Richard H. "A stabilization of the simplex method." + Journal in Numerische Mathematik 16.5 (1971): 414-434. + +""" +# Author: Matt Haberland + +import numpy as np +from numpy.linalg import LinAlgError + +from scipy.linalg import solve +from ._optimize import _check_unknown_options +from ._bglu_dense import LU +from ._bglu_dense import BGLU as BGLU +from ._linprog_util import _postsolve +from ._optimize import OptimizeResult + + +def _phase_one(A, b, x0, callback, postsolve_args, maxiter, tol, disp, + maxupdate, mast, pivot): + """ + The purpose of phase one is to find an initial basic feasible solution + (BFS) to the original problem. + + Generates an auxiliary problem with a trivial BFS and an objective that + minimizes infeasibility of the original problem. Solves the auxiliary + problem using the main simplex routine (phase two). This either yields + a BFS to the original problem or determines that the original problem is + infeasible. If feasible, phase one detects redundant rows in the original + constraint matrix and removes them, then chooses additional indices as + necessary to complete a basis/BFS for the original problem. + """ + + m, n = A.shape + status = 0 + + # generate auxiliary problem to get initial BFS + A, b, c, basis, x, status = _generate_auxiliary_problem(A, b, x0, tol) + + if status == 6: + residual = c.dot(x) + iter_k = 0 + return x, basis, A, b, residual, status, iter_k + + # solve auxiliary problem + phase_one_n = n + iter_k = 0 + x, basis, status, iter_k = _phase_two(c, A, x, basis, callback, + postsolve_args, + maxiter, tol, disp, + maxupdate, mast, pivot, + iter_k, phase_one_n) + + # check for infeasibility + residual = c.dot(x) + if status == 0 and residual > tol: + status = 2 + + # drive artificial variables out of basis + # TODO: test redundant row removal better + # TODO: make solve more efficient with BGLU? This could take a while. + keep_rows = np.ones(m, dtype=bool) + for basis_column in basis[basis >= n]: + B = A[:, basis] + try: + basis_finder = np.abs(solve(B, A)) # inefficient + pertinent_row = np.argmax(basis_finder[:, basis_column]) + eligible_columns = np.ones(n, dtype=bool) + eligible_columns[basis[basis < n]] = 0 + eligible_column_indices = np.where(eligible_columns)[0] + index = np.argmax(basis_finder[:, :n] + [pertinent_row, eligible_columns]) + new_basis_column = eligible_column_indices[index] + if basis_finder[pertinent_row, new_basis_column] < tol: + keep_rows[pertinent_row] = False + else: + basis[basis == basis_column] = new_basis_column + except LinAlgError: + status = 4 + + # form solution to original problem + A = A[keep_rows, :n] + basis = basis[keep_rows] + x = x[:n] + m = A.shape[0] + return x, basis, A, b, residual, status, iter_k + + +def _get_more_basis_columns(A, basis): + """ + Called when the auxiliary problem terminates with artificial columns in + the basis, which must be removed and replaced with non-artificial + columns. Finds additional columns that do not make the matrix singular. + """ + m, n = A.shape + + # options for inclusion are those that aren't already in the basis + a = np.arange(m+n) + bl = np.zeros(len(a), dtype=bool) + bl[basis] = 1 + options = a[~bl] + options = options[options < n] # and they have to be non-artificial + + # form basis matrix + B = np.zeros((m, m)) + B[:, 0:len(basis)] = A[:, basis] + + if (basis.size > 0 and + np.linalg.matrix_rank(B[:, :len(basis)]) < len(basis)): + raise Exception("Basis has dependent columns") + + rank = 0 # just enter the loop + for i in range(n): # somewhat arbitrary, but we need another way out + # permute the options, and take as many as needed + new_basis = np.random.permutation(options)[:m-len(basis)] + B[:, len(basis):] = A[:, new_basis] # update the basis matrix + rank = np.linalg.matrix_rank(B) # check the rank + if rank == m: + break + + return np.concatenate((basis, new_basis)) + + +def _generate_auxiliary_problem(A, b, x0, tol): + """ + Modifies original problem to create an auxiliary problem with a trivial + initial basic feasible solution and an objective that minimizes + infeasibility in the original problem. + + Conceptually, this is done by stacking an identity matrix on the right of + the original constraint matrix, adding artificial variables to correspond + with each of these new columns, and generating a cost vector that is all + zeros except for ones corresponding with each of the new variables. + + A initial basic feasible solution is trivial: all variables are zero + except for the artificial variables, which are set equal to the + corresponding element of the right hand side `b`. + + Running the simplex method on this auxiliary problem drives all of the + artificial variables - and thus the cost - to zero if the original problem + is feasible. The original problem is declared infeasible otherwise. + + Much of the complexity below is to improve efficiency by using singleton + columns in the original problem where possible, thus generating artificial + variables only as necessary, and using an initial 'guess' basic feasible + solution. + """ + status = 0 + m, n = A.shape + + if x0 is not None: + x = x0 + else: + x = np.zeros(n) + + r = b - A@x # residual; this must be all zeros for feasibility + + A[r < 0] = -A[r < 0] # express problem with RHS positive for trivial BFS + b[r < 0] = -b[r < 0] # to the auxiliary problem + r[r < 0] *= -1 + + # Rows which we will need to find a trivial way to zero. + # This should just be the rows where there is a nonzero residual. + # But then we would not necessarily have a column singleton in every row. + # This makes it difficult to find an initial basis. + if x0 is None: + nonzero_constraints = np.arange(m) + else: + nonzero_constraints = np.where(r > tol)[0] + + # these are (at least some of) the initial basis columns + basis = np.where(np.abs(x) > tol)[0] + + if len(nonzero_constraints) == 0 and len(basis) <= m: # already a BFS + c = np.zeros(n) + basis = _get_more_basis_columns(A, basis) + return A, b, c, basis, x, status + elif (len(nonzero_constraints) > m - len(basis) or + np.any(x < 0)): # can't get trivial BFS + c = np.zeros(n) + status = 6 + return A, b, c, basis, x, status + + # chooses existing columns appropriate for inclusion in initial basis + cols, rows = _select_singleton_columns(A, r) + + # find the rows we need to zero that we _can_ zero with column singletons + i_tofix = np.isin(rows, nonzero_constraints) + # these columns can't already be in the basis, though + # we are going to add them to the basis and change the corresponding x val + i_notinbasis = np.logical_not(np.isin(cols, basis)) + i_fix_without_aux = np.logical_and(i_tofix, i_notinbasis) + rows = rows[i_fix_without_aux] + cols = cols[i_fix_without_aux] + + # indices of the rows we can only zero with auxiliary variable + # these rows will get a one in each auxiliary column + arows = nonzero_constraints[np.logical_not( + np.isin(nonzero_constraints, rows))] + n_aux = len(arows) + acols = n + np.arange(n_aux) # indices of auxiliary columns + + basis_ng = np.concatenate((cols, acols)) # basis columns not from guess + basis_ng_rows = np.concatenate((rows, arows)) # rows we need to zero + + # add auxiliary singleton columns + A = np.hstack((A, np.zeros((m, n_aux)))) + A[arows, acols] = 1 + + # generate initial BFS + x = np.concatenate((x, np.zeros(n_aux))) + x[basis_ng] = r[basis_ng_rows]/A[basis_ng_rows, basis_ng] + + # generate costs to minimize infeasibility + c = np.zeros(n_aux + n) + c[acols] = 1 + + # basis columns correspond with nonzeros in guess, those with column + # singletons we used to zero remaining constraints, and any additional + # columns to get a full set (m columns) + basis = np.concatenate((basis, basis_ng)) + basis = _get_more_basis_columns(A, basis) # add columns as needed + + return A, b, c, basis, x, status + + +def _select_singleton_columns(A, b): + """ + Finds singleton columns for which the singleton entry is of the same sign + as the right-hand side; these columns are eligible for inclusion in an + initial basis. Determines the rows in which the singleton entries are + located. For each of these rows, returns the indices of the one singleton + column and its corresponding row. + """ + # find indices of all singleton columns and corresponding row indices + column_indices = np.nonzero(np.sum(np.abs(A) != 0, axis=0) == 1)[0] + columns = A[:, column_indices] # array of singleton columns + row_indices = np.zeros(len(column_indices), dtype=int) + nonzero_rows, nonzero_columns = np.nonzero(columns) + row_indices[nonzero_columns] = nonzero_rows # corresponding row indices + + # keep only singletons with entries that have same sign as RHS + # this is necessary because all elements of BFS must be non-negative + same_sign = A[row_indices, column_indices]*b[row_indices] >= 0 + column_indices = column_indices[same_sign][::-1] + row_indices = row_indices[same_sign][::-1] + # Reversing the order so that steps below select rightmost columns + # for initial basis, which will tend to be slack variables. (If the + # guess corresponds with a basic feasible solution but a constraint + # is not satisfied with the corresponding slack variable zero, the slack + # variable must be basic.) + + # for each row, keep rightmost singleton column with an entry in that row + unique_row_indices, first_columns = np.unique(row_indices, + return_index=True) + return column_indices[first_columns], unique_row_indices + + +def _find_nonzero_rows(A, tol): + """ + Returns logical array indicating the locations of rows with at least + one nonzero element. + """ + return np.any(np.abs(A) > tol, axis=1) + + +def _select_enter_pivot(c_hat, bl, a, rule="bland", tol=1e-12): + """ + Selects a pivot to enter the basis. Currently Bland's rule - the smallest + index that has a negative reduced cost - is the default. + """ + if rule.lower() == "mrc": # index with minimum reduced cost + return a[~bl][np.argmin(c_hat)] + else: # smallest index w/ negative reduced cost + return a[~bl][c_hat < -tol][0] + + +def _display_iter(phase, iteration, slack, con, fun): + """ + Print indicators of optimization status to the console. + """ + header = True if not iteration % 20 else False + + if header: + print("Phase", + "Iteration", + "Minimum Slack ", + "Constraint Residual", + "Objective ") + + # := -tol): # all reduced costs positive -> terminate + break + + j = _select_enter_pivot(c_hat, bl, a, rule=pivot, tol=tol) + u = B.solve(A[:, j]) # similar to u = solve(B, A[:, j]) + + i = u > tol # if none of the u are positive, unbounded + if not np.any(i): + status = 3 + break + + th = xb[i]/u[i] + l = np.argmin(th) # implicitly selects smallest subscript + th_star = th[l] # step size + + x[b] = x[b] - th_star*u # take step + x[j] = th_star + B.update(ab[i][l], j) # modify basis + b = B.b # similar to b[ab[i][l]] = + + else: + # If the end of the for loop is reached (without a break statement), + # then another step has been taken, so the iteration counter should + # increment, info should be displayed, and callback should be called. + iteration += 1 + status = 1 + if disp or callback is not None: + _display_and_callback(phase_one_n, x, postsolve_args, status, + iteration, disp, callback) + + return x, b, status, iteration + + +def _linprog_rs(c, c0, A, b, x0, callback, postsolve_args, + maxiter=5000, tol=1e-12, disp=False, + maxupdate=10, mast=False, pivot="mrc", + **unknown_options): + """ + Solve the following linear programming problem via a two-phase + revised simplex algorithm.:: + + minimize: c @ x + + subject to: A @ x == b + 0 <= x < oo + + User-facing documentation is in _linprog_doc.py. + + Parameters + ---------- + c : 1-D array + Coefficients of the linear objective function to be minimized. + c0 : float + Constant term in objective function due to fixed (and eliminated) + variables. (Currently unused.) + A : 2-D array + 2-D array which, when matrix-multiplied by ``x``, gives the values of + the equality constraints at ``x``. + b : 1-D array + 1-D array of values representing the RHS of each equality constraint + (row) in ``A_eq``. + x0 : 1-D array, optional + Starting values of the independent variables, which will be refined by + the optimization algorithm. For the revised simplex method, these must + correspond with a basic feasible solution. + callback : callable, optional + If a callback function is provided, it will be called within each + iteration of the algorithm. The callback function must accept a single + `scipy.optimize.OptimizeResult` consisting of the following fields: + + x : 1-D array + Current solution vector. + fun : float + Current value of the objective function ``c @ x``. + success : bool + True only when an algorithm has completed successfully, + so this is always False as the callback function is called + only while the algorithm is still iterating. + slack : 1-D array + The values of the slack variables. Each slack variable + corresponds to an inequality constraint. If the slack is zero, + the corresponding constraint is active. + con : 1-D array + The (nominally zero) residuals of the equality constraints, + that is, ``b - A_eq @ x``. + phase : int + The phase of the algorithm being executed. + status : int + For revised simplex, this is always 0 because if a different + status is detected, the algorithm terminates. + nit : int + The number of iterations performed. + message : str + A string descriptor of the exit status of the optimization. + postsolve_args : tuple + Data needed by _postsolve to convert the solution to the standard-form + problem into the solution to the original problem. + + Options + ------- + maxiter : int + The maximum number of iterations to perform in either phase. + tol : float + The tolerance which determines when a solution is "close enough" to + zero in Phase 1 to be considered a basic feasible solution or close + enough to positive to serve as an optimal solution. + disp : bool + Set to ``True`` if indicators of optimization status are to be printed + to the console each iteration. + maxupdate : int + The maximum number of updates performed on the LU factorization. + After this many updates is reached, the basis matrix is factorized + from scratch. + mast : bool + Minimize Amortized Solve Time. If enabled, the average time to solve + a linear system using the basis factorization is measured. Typically, + the average solve time will decrease with each successive solve after + initial factorization, as factorization takes much more time than the + solve operation (and updates). Eventually, however, the updated + factorization becomes sufficiently complex that the average solve time + begins to increase. When this is detected, the basis is refactorized + from scratch. Enable this option to maximize speed at the risk of + nondeterministic behavior. Ignored if ``maxupdate`` is 0. + pivot : "mrc" or "bland" + Pivot rule: Minimum Reduced Cost (default) or Bland's rule. Choose + Bland's rule if iteration limit is reached and cycling is suspected. + unknown_options : dict + Optional arguments not used by this particular solver. If + `unknown_options` is non-empty a warning is issued listing all + unused options. + + Returns + ------- + x : 1-D array + Solution vector. + status : int + An integer representing the exit status of the optimization:: + + 0 : Optimization terminated successfully + 1 : Iteration limit reached + 2 : Problem appears to be infeasible + 3 : Problem appears to be unbounded + 4 : Numerical difficulties encountered + 5 : No constraints; turn presolve on + 6 : Guess x0 cannot be converted to a basic feasible solution + + message : str + A string descriptor of the exit status of the optimization. + iteration : int + The number of iterations taken to solve the problem. + """ + + _check_unknown_options(unknown_options) + + messages = ["Optimization terminated successfully.", + "Iteration limit reached.", + "The problem appears infeasible, as the phase one auxiliary " + "problem terminated successfully with a residual of {0:.1e}, " + "greater than the tolerance {1} required for the solution to " + "be considered feasible. Consider increasing the tolerance to " + "be greater than {0:.1e}. If this tolerance is unnaceptably " + "large, the problem is likely infeasible.", + "The problem is unbounded, as the simplex algorithm found " + "a basic feasible solution from which there is a direction " + "with negative reduced cost in which all decision variables " + "increase.", + "Numerical difficulties encountered; consider trying " + "method='interior-point'.", + "Problems with no constraints are trivially solved; please " + "turn presolve on.", + "The guess x0 cannot be converted to a basic feasible " + "solution. " + ] + + if A.size == 0: # address test_unbounded_below_no_presolve_corrected + return np.zeros(c.shape), 5, messages[5], 0 + + x, basis, A, b, residual, status, iteration = ( + _phase_one(A, b, x0, callback, postsolve_args, + maxiter, tol, disp, maxupdate, mast, pivot)) + + if status == 0: + x, basis, status, iteration = _phase_two(c, A, x, basis, callback, + postsolve_args, + maxiter, tol, disp, + maxupdate, mast, pivot, + iteration) + + return x, status, messages[status].format(residual, tol), iteration diff --git a/llava_next/lib/python3.10/site-packages/scipy/optimize/_lsap.cpython-310-x86_64-linux-gnu.so b/llava_next/lib/python3.10/site-packages/scipy/optimize/_lsap.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..b2ea39a10549d1346bada989f573981804d22006 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/scipy/optimize/_lsap.cpython-310-x86_64-linux-gnu.so differ diff --git a/llava_next/lib/python3.10/site-packages/scipy/optimize/_milp.py b/llava_next/lib/python3.10/site-packages/scipy/optimize/_milp.py new file mode 100644 index 0000000000000000000000000000000000000000..5ec771eba471e37aac5aa3008b642f68167fbafb --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/scipy/optimize/_milp.py @@ -0,0 +1,392 @@ +import warnings +import numpy as np +from scipy.sparse import csc_array, vstack, issparse +from scipy._lib._util import VisibleDeprecationWarning +from ._highs._highs_wrapper import _highs_wrapper # type: ignore[import-not-found,import-untyped] +from ._constraints import LinearConstraint, Bounds +from ._optimize import OptimizeResult +from ._linprog_highs import _highs_to_scipy_status_message + + +def _constraints_to_components(constraints): + """ + Convert sequence of constraints to a single set of components A, b_l, b_u. + + `constraints` could be + + 1. A LinearConstraint + 2. A tuple representing a LinearConstraint + 3. An invalid object + 4. A sequence of composed entirely of objects of type 1/2 + 5. A sequence containing at least one object of type 3 + + We want to accept 1, 2, and 4 and reject 3 and 5. + """ + message = ("`constraints` (or each element within `constraints`) must be " + "convertible into an instance of " + "`scipy.optimize.LinearConstraint`.") + As = [] + b_ls = [] + b_us = [] + + # Accept case 1 by standardizing as case 4 + if isinstance(constraints, LinearConstraint): + constraints = [constraints] + else: + # Reject case 3 + try: + iter(constraints) + except TypeError as exc: + raise ValueError(message) from exc + + # Accept case 2 by standardizing as case 4 + if len(constraints) == 3: + # argument could be a single tuple representing a LinearConstraint + try: + constraints = [LinearConstraint(*constraints)] + except (TypeError, ValueError, VisibleDeprecationWarning): + # argument was not a tuple representing a LinearConstraint + pass + + # Address cases 4/5 + for constraint in constraints: + # if it's not a LinearConstraint or something that represents a + # LinearConstraint at this point, it's invalid + if not isinstance(constraint, LinearConstraint): + try: + constraint = LinearConstraint(*constraint) + except TypeError as exc: + raise ValueError(message) from exc + As.append(csc_array(constraint.A)) + b_ls.append(np.atleast_1d(constraint.lb).astype(np.float64)) + b_us.append(np.atleast_1d(constraint.ub).astype(np.float64)) + + if len(As) > 1: + A = vstack(As, format="csc") + b_l = np.concatenate(b_ls) + b_u = np.concatenate(b_us) + else: # avoid unnecessary copying + A = As[0] + b_l = b_ls[0] + b_u = b_us[0] + + return A, b_l, b_u + + +def _milp_iv(c, integrality, bounds, constraints, options): + # objective IV + if issparse(c): + raise ValueError("`c` must be a dense array.") + c = np.atleast_1d(c).astype(np.float64) + if c.ndim != 1 or c.size == 0 or not np.all(np.isfinite(c)): + message = ("`c` must be a one-dimensional array of finite numbers " + "with at least one element.") + raise ValueError(message) + + # integrality IV + if issparse(integrality): + raise ValueError("`integrality` must be a dense array.") + message = ("`integrality` must contain integers 0-3 and be broadcastable " + "to `c.shape`.") + if integrality is None: + integrality = 0 + try: + integrality = np.broadcast_to(integrality, c.shape).astype(np.uint8) + except ValueError: + raise ValueError(message) + if integrality.min() < 0 or integrality.max() > 3: + raise ValueError(message) + + # bounds IV + if bounds is None: + bounds = Bounds(0, np.inf) + elif not isinstance(bounds, Bounds): + message = ("`bounds` must be convertible into an instance of " + "`scipy.optimize.Bounds`.") + try: + bounds = Bounds(*bounds) + except TypeError as exc: + raise ValueError(message) from exc + + try: + lb = np.broadcast_to(bounds.lb, c.shape).astype(np.float64) + ub = np.broadcast_to(bounds.ub, c.shape).astype(np.float64) + except (ValueError, TypeError) as exc: + message = ("`bounds.lb` and `bounds.ub` must contain reals and " + "be broadcastable to `c.shape`.") + raise ValueError(message) from exc + + # constraints IV + if not constraints: + constraints = [LinearConstraint(np.empty((0, c.size)), + np.empty((0,)), np.empty((0,)))] + try: + A, b_l, b_u = _constraints_to_components(constraints) + except ValueError as exc: + message = ("`constraints` (or each element within `constraints`) must " + "be convertible into an instance of " + "`scipy.optimize.LinearConstraint`.") + raise ValueError(message) from exc + + if A.shape != (b_l.size, c.size): + message = "The shape of `A` must be (len(b_l), len(c))." + raise ValueError(message) + indptr, indices, data = A.indptr, A.indices, A.data.astype(np.float64) + + # options IV + options = options or {} + supported_options = {'disp', 'presolve', 'time_limit', 'node_limit', + 'mip_rel_gap'} + unsupported_options = set(options).difference(supported_options) + if unsupported_options: + message = (f"Unrecognized options detected: {unsupported_options}. " + "These will be passed to HiGHS verbatim.") + warnings.warn(message, RuntimeWarning, stacklevel=3) + options_iv = {'log_to_console': options.pop("disp", False), + 'mip_max_nodes': options.pop("node_limit", None)} + options_iv.update(options) + + return c, integrality, lb, ub, indptr, indices, data, b_l, b_u, options_iv + + +def milp(c, *, integrality=None, bounds=None, constraints=None, options=None): + r""" + Mixed-integer linear programming + + Solves problems of the following form: + + .. math:: + + \min_x \ & c^T x \\ + \mbox{such that} \ & b_l \leq A x \leq b_u,\\ + & l \leq x \leq u, \\ + & x_i \in \mathbb{Z}, i \in X_i + + where :math:`x` is a vector of decision variables; + :math:`c`, :math:`b_l`, :math:`b_u`, :math:`l`, and :math:`u` are vectors; + :math:`A` is a matrix, and :math:`X_i` is the set of indices of + decision variables that must be integral. (In this context, a + variable that can assume only integer values is said to be "integral"; + it has an "integrality" constraint.) + + Alternatively, that's: + + minimize:: + + c @ x + + such that:: + + b_l <= A @ x <= b_u + l <= x <= u + Specified elements of x must be integers + + By default, ``l = 0`` and ``u = np.inf`` unless specified with + ``bounds``. + + Parameters + ---------- + c : 1D dense array_like + The coefficients of the linear objective function to be minimized. + `c` is converted to a double precision array before the problem is + solved. + integrality : 1D dense array_like, optional + Indicates the type of integrality constraint on each decision variable. + + ``0`` : Continuous variable; no integrality constraint. + + ``1`` : Integer variable; decision variable must be an integer + within `bounds`. + + ``2`` : Semi-continuous variable; decision variable must be within + `bounds` or take value ``0``. + + ``3`` : Semi-integer variable; decision variable must be an integer + within `bounds` or take value ``0``. + + By default, all variables are continuous. `integrality` is converted + to an array of integers before the problem is solved. + + bounds : scipy.optimize.Bounds, optional + Bounds on the decision variables. Lower and upper bounds are converted + to double precision arrays before the problem is solved. The + ``keep_feasible`` parameter of the `Bounds` object is ignored. If + not specified, all decision variables are constrained to be + non-negative. + constraints : sequence of scipy.optimize.LinearConstraint, optional + Linear constraints of the optimization problem. Arguments may be + one of the following: + + 1. A single `LinearConstraint` object + 2. A single tuple that can be converted to a `LinearConstraint` object + as ``LinearConstraint(*constraints)`` + 3. A sequence composed entirely of objects of type 1. and 2. + + Before the problem is solved, all values are converted to double + precision, and the matrices of constraint coefficients are converted to + instances of `scipy.sparse.csc_array`. The ``keep_feasible`` parameter + of `LinearConstraint` objects is ignored. + options : dict, optional + A dictionary of solver options. The following keys are recognized. + + disp : bool (default: ``False``) + Set to ``True`` if indicators of optimization status are to be + printed to the console during optimization. + node_limit : int, optional + The maximum number of nodes (linear program relaxations) to solve + before stopping. Default is no maximum number of nodes. + presolve : bool (default: ``True``) + Presolve attempts to identify trivial infeasibilities, + identify trivial unboundedness, and simplify the problem before + sending it to the main solver. + time_limit : float, optional + The maximum number of seconds allotted to solve the problem. + Default is no time limit. + mip_rel_gap : float, optional + Termination criterion for MIP solver: solver will terminate when + the gap between the primal objective value and the dual objective + bound, scaled by the primal objective value, is <= mip_rel_gap. + + Returns + ------- + res : OptimizeResult + An instance of :class:`scipy.optimize.OptimizeResult`. The object + is guaranteed to have the following attributes. + + status : int + An integer representing the exit status of the algorithm. + + ``0`` : Optimal solution found. + + ``1`` : Iteration or time limit reached. + + ``2`` : Problem is infeasible. + + ``3`` : Problem is unbounded. + + ``4`` : Other; see message for details. + + success : bool + ``True`` when an optimal solution is found and ``False`` otherwise. + + message : str + A string descriptor of the exit status of the algorithm. + + The following attributes will also be present, but the values may be + ``None``, depending on the solution status. + + x : ndarray + The values of the decision variables that minimize the + objective function while satisfying the constraints. + fun : float + The optimal value of the objective function ``c @ x``. + mip_node_count : int + The number of subproblems or "nodes" solved by the MILP solver. + mip_dual_bound : float + The MILP solver's final estimate of the lower bound on the optimal + solution. + mip_gap : float + The difference between the primal objective value and the dual + objective bound, scaled by the primal objective value. + + Notes + ----- + `milp` is a wrapper of the HiGHS linear optimization software [1]_. The + algorithm is deterministic, and it typically finds the global optimum of + moderately challenging mixed-integer linear programs (when it exists). + + References + ---------- + .. [1] Huangfu, Q., Galabova, I., Feldmeier, M., and Hall, J. A. J. + "HiGHS - high performance software for linear optimization." + https://highs.dev/ + .. [2] Huangfu, Q. and Hall, J. A. J. "Parallelizing the dual revised + simplex method." Mathematical Programming Computation, 10 (1), + 119-142, 2018. DOI: 10.1007/s12532-017-0130-5 + + Examples + -------- + Consider the problem at + https://en.wikipedia.org/wiki/Integer_programming#Example, which is + expressed as a maximization problem of two variables. Since `milp` requires + that the problem be expressed as a minimization problem, the objective + function coefficients on the decision variables are: + + >>> import numpy as np + >>> c = -np.array([0, 1]) + + Note the negative sign: we maximize the original objective function + by minimizing the negative of the objective function. + + We collect the coefficients of the constraints into arrays like: + + >>> A = np.array([[-1, 1], [3, 2], [2, 3]]) + >>> b_u = np.array([1, 12, 12]) + >>> b_l = np.full_like(b_u, -np.inf, dtype=float) + + Because there is no lower limit on these constraints, we have defined a + variable ``b_l`` full of values representing negative infinity. This may + be unfamiliar to users of `scipy.optimize.linprog`, which only accepts + "less than" (or "upper bound") inequality constraints of the form + ``A_ub @ x <= b_u``. By accepting both ``b_l`` and ``b_u`` of constraints + ``b_l <= A_ub @ x <= b_u``, `milp` makes it easy to specify "greater than" + inequality constraints, "less than" inequality constraints, and equality + constraints concisely. + + These arrays are collected into a single `LinearConstraint` object like: + + >>> from scipy.optimize import LinearConstraint + >>> constraints = LinearConstraint(A, b_l, b_u) + + The non-negativity bounds on the decision variables are enforced by + default, so we do not need to provide an argument for `bounds`. + + Finally, the problem states that both decision variables must be integers: + + >>> integrality = np.ones_like(c) + + We solve the problem like: + + >>> from scipy.optimize import milp + >>> res = milp(c=c, constraints=constraints, integrality=integrality) + >>> res.x + [2.0, 2.0] + + Note that had we solved the relaxed problem (without integrality + constraints): + + >>> res = milp(c=c, constraints=constraints) # OR: + >>> # from scipy.optimize import linprog; res = linprog(c, A, b_u) + >>> res.x + [1.8, 2.8] + + we would not have obtained the correct solution by rounding to the nearest + integers. + + Other examples are given :ref:`in the tutorial `. + + """ + args_iv = _milp_iv(c, integrality, bounds, constraints, options) + c, integrality, lb, ub, indptr, indices, data, b_l, b_u, options = args_iv + + highs_res = _highs_wrapper(c, indptr, indices, data, b_l, b_u, + lb, ub, integrality, options) + + res = {} + + # Convert to scipy-style status and message + highs_status = highs_res.get('status', None) + highs_message = highs_res.get('message', None) + status, message = _highs_to_scipy_status_message(highs_status, + highs_message) + res['status'] = status + res['message'] = message + res['success'] = (status == 0) + x = highs_res.get('x', None) + res['x'] = np.array(x) if x is not None else None + res['fun'] = highs_res.get('fun', None) + res['mip_node_count'] = highs_res.get('mip_node_count', None) + res['mip_dual_bound'] = highs_res.get('mip_dual_bound', None) + res['mip_gap'] = highs_res.get('mip_gap', None) + + return OptimizeResult(res) diff --git a/llava_next/lib/python3.10/site-packages/scipy/optimize/_minpack.cpython-310-x86_64-linux-gnu.so b/llava_next/lib/python3.10/site-packages/scipy/optimize/_minpack.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..f747929147c24b2502a9738995f0a74f8753db99 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/scipy/optimize/_minpack.cpython-310-x86_64-linux-gnu.so differ diff --git a/llava_next/lib/python3.10/site-packages/scipy/optimize/_minpack_py.py b/llava_next/lib/python3.10/site-packages/scipy/optimize/_minpack_py.py new file mode 100644 index 0000000000000000000000000000000000000000..b67a17ae41b4db6633918aa0b318fae88d56d5f7 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/scipy/optimize/_minpack_py.py @@ -0,0 +1,1164 @@ +import warnings +from . import _minpack + +import numpy as np +from numpy import (atleast_1d, triu, shape, transpose, zeros, prod, greater, + asarray, inf, + finfo, inexact, issubdtype, dtype) +from scipy import linalg +from scipy.linalg import svd, cholesky, solve_triangular, LinAlgError +from scipy._lib._util import _asarray_validated, _lazywhere, _contains_nan +from scipy._lib._util import getfullargspec_no_self as _getfullargspec +from ._optimize import OptimizeResult, _check_unknown_options, OptimizeWarning +from ._lsq import least_squares +# from ._lsq.common import make_strictly_feasible +from ._lsq.least_squares import prepare_bounds +from scipy.optimize._minimize import Bounds + +__all__ = ['fsolve', 'leastsq', 'fixed_point', 'curve_fit'] + + +def _check_func(checker, argname, thefunc, x0, args, numinputs, + output_shape=None): + res = atleast_1d(thefunc(*((x0[:numinputs],) + args))) + if (output_shape is not None) and (shape(res) != output_shape): + if (output_shape[0] != 1): + if len(output_shape) > 1: + if output_shape[1] == 1: + return shape(res) + msg = f"{checker}: there is a mismatch between the input and output " \ + f"shape of the '{argname}' argument" + func_name = getattr(thefunc, '__name__', None) + if func_name: + msg += " '%s'." % func_name + else: + msg += "." + msg += f'Shape should be {output_shape} but it is {shape(res)}.' + raise TypeError(msg) + if issubdtype(res.dtype, inexact): + dt = res.dtype + else: + dt = dtype(float) + return shape(res), dt + + +def fsolve(func, x0, args=(), fprime=None, full_output=0, + col_deriv=0, xtol=1.49012e-8, maxfev=0, band=None, + epsfcn=None, factor=100, diag=None): + """ + Find the roots of a function. + + Return the roots of the (non-linear) equations defined by + ``func(x) = 0`` given a starting estimate. + + Parameters + ---------- + func : callable ``f(x, *args)`` + A function that takes at least one (possibly vector) argument, + and returns a value of the same length. + x0 : ndarray + The starting estimate for the roots of ``func(x) = 0``. + args : tuple, optional + Any extra arguments to `func`. + fprime : callable ``f(x, *args)``, optional + A function to compute the Jacobian of `func` with derivatives + across the rows. By default, the Jacobian will be estimated. + full_output : bool, optional + If True, return optional outputs. + col_deriv : bool, optional + Specify whether the Jacobian function computes derivatives down + the columns (faster, because there is no transpose operation). + xtol : float, optional + The calculation will terminate if the relative error between two + consecutive iterates is at most `xtol`. + maxfev : int, optional + The maximum number of calls to the function. If zero, then + ``100*(N+1)`` is the maximum where N is the number of elements + in `x0`. + band : tuple, optional + If set to a two-sequence containing the number of sub- and + super-diagonals within the band of the Jacobi matrix, the + Jacobi matrix is considered banded (only for ``fprime=None``). + epsfcn : float, optional + A suitable step length for the forward-difference + approximation of the Jacobian (for ``fprime=None``). If + `epsfcn` is less than the machine precision, it is assumed + that the relative errors in the functions are of the order of + the machine precision. + factor : float, optional + A parameter determining the initial step bound + (``factor * || diag * x||``). Should be in the interval + ``(0.1, 100)``. + diag : sequence, optional + N positive entries that serve as a scale factors for the + variables. + + Returns + ------- + x : ndarray + The solution (or the result of the last iteration for + an unsuccessful call). + infodict : dict + A dictionary of optional outputs with the keys: + + ``nfev`` + number of function calls + ``njev`` + number of Jacobian calls + ``fvec`` + function evaluated at the output + ``fjac`` + the orthogonal matrix, q, produced by the QR + factorization of the final approximate Jacobian + matrix, stored column wise + ``r`` + upper triangular matrix produced by QR factorization + of the same matrix + ``qtf`` + the vector ``(transpose(q) * fvec)`` + + ier : int + An integer flag. Set to 1 if a solution was found, otherwise refer + to `mesg` for more information. + mesg : str + If no solution is found, `mesg` details the cause of failure. + + See Also + -------- + root : Interface to root finding algorithms for multivariate + functions. See the ``method='hybr'`` in particular. + + Notes + ----- + ``fsolve`` is a wrapper around MINPACK's hybrd and hybrj algorithms. + + Examples + -------- + Find a solution to the system of equations: + ``x0*cos(x1) = 4, x1*x0 - x1 = 5``. + + >>> import numpy as np + >>> from scipy.optimize import fsolve + >>> def func(x): + ... return [x[0] * np.cos(x[1]) - 4, + ... x[1] * x[0] - x[1] - 5] + >>> root = fsolve(func, [1, 1]) + >>> root + array([6.50409711, 0.90841421]) + >>> np.isclose(func(root), [0.0, 0.0]) # func(root) should be almost 0.0. + array([ True, True]) + + """ + def _wrapped_func(*fargs): + """ + Wrapped `func` to track the number of times + the function has been called. + """ + _wrapped_func.nfev += 1 + return func(*fargs) + + _wrapped_func.nfev = 0 + + options = {'col_deriv': col_deriv, + 'xtol': xtol, + 'maxfev': maxfev, + 'band': band, + 'eps': epsfcn, + 'factor': factor, + 'diag': diag} + + res = _root_hybr(_wrapped_func, x0, args, jac=fprime, **options) + res.nfev = _wrapped_func.nfev + + if full_output: + x = res['x'] + info = {k: res.get(k) + for k in ('nfev', 'njev', 'fjac', 'r', 'qtf') if k in res} + info['fvec'] = res['fun'] + return x, info, res['status'], res['message'] + else: + status = res['status'] + msg = res['message'] + if status == 0: + raise TypeError(msg) + elif status == 1: + pass + elif status in [2, 3, 4, 5]: + warnings.warn(msg, RuntimeWarning, stacklevel=2) + else: + raise TypeError(msg) + return res['x'] + + +def _root_hybr(func, x0, args=(), jac=None, + col_deriv=0, xtol=1.49012e-08, maxfev=0, band=None, eps=None, + factor=100, diag=None, **unknown_options): + """ + Find the roots of a multivariate function using MINPACK's hybrd and + hybrj routines (modified Powell method). + + Options + ------- + col_deriv : bool + Specify whether the Jacobian function computes derivatives down + the columns (faster, because there is no transpose operation). + xtol : float + The calculation will terminate if the relative error between two + consecutive iterates is at most `xtol`. + maxfev : int + The maximum number of calls to the function. If zero, then + ``100*(N+1)`` is the maximum where N is the number of elements + in `x0`. + band : tuple + If set to a two-sequence containing the number of sub- and + super-diagonals within the band of the Jacobi matrix, the + Jacobi matrix is considered banded (only for ``fprime=None``). + eps : float + A suitable step length for the forward-difference + approximation of the Jacobian (for ``fprime=None``). If + `eps` is less than the machine precision, it is assumed + that the relative errors in the functions are of the order of + the machine precision. + factor : float + A parameter determining the initial step bound + (``factor * || diag * x||``). Should be in the interval + ``(0.1, 100)``. + diag : sequence + N positive entries that serve as a scale factors for the + variables. + + """ + _check_unknown_options(unknown_options) + epsfcn = eps + + x0 = asarray(x0).flatten() + n = len(x0) + if not isinstance(args, tuple): + args = (args,) + shape, dtype = _check_func('fsolve', 'func', func, x0, args, n, (n,)) + if epsfcn is None: + epsfcn = finfo(dtype).eps + Dfun = jac + if Dfun is None: + if band is None: + ml, mu = -10, -10 + else: + ml, mu = band[:2] + if maxfev == 0: + maxfev = 200 * (n + 1) + retval = _minpack._hybrd(func, x0, args, 1, xtol, maxfev, + ml, mu, epsfcn, factor, diag) + else: + _check_func('fsolve', 'fprime', Dfun, x0, args, n, (n, n)) + if (maxfev == 0): + maxfev = 100 * (n + 1) + retval = _minpack._hybrj(func, Dfun, x0, args, 1, + col_deriv, xtol, maxfev, factor, diag) + + x, status = retval[0], retval[-1] + + errors = {0: "Improper input parameters were entered.", + 1: "The solution converged.", + 2: "The number of calls to function has " + "reached maxfev = %d." % maxfev, + 3: "xtol=%f is too small, no further improvement " + "in the approximate\n solution " + "is possible." % xtol, + 4: "The iteration is not making good progress, as measured " + "by the \n improvement from the last five " + "Jacobian evaluations.", + 5: "The iteration is not making good progress, " + "as measured by the \n improvement from the last " + "ten iterations.", + 'unknown': "An error occurred."} + + info = retval[1] + info['fun'] = info.pop('fvec') + sol = OptimizeResult(x=x, success=(status == 1), status=status, + method="hybr") + sol.update(info) + try: + sol['message'] = errors[status] + except KeyError: + sol['message'] = errors['unknown'] + + return sol + + +LEASTSQ_SUCCESS = [1, 2, 3, 4] +LEASTSQ_FAILURE = [5, 6, 7, 8] + + +def leastsq(func, x0, args=(), Dfun=None, full_output=False, + col_deriv=False, ftol=1.49012e-8, xtol=1.49012e-8, + gtol=0.0, maxfev=0, epsfcn=None, factor=100, diag=None): + """ + Minimize the sum of squares of a set of equations. + + :: + + x = arg min(sum(func(y)**2,axis=0)) + y + + Parameters + ---------- + func : callable + Should take at least one (possibly length ``N`` vector) argument and + returns ``M`` floating point numbers. It must not return NaNs or + fitting might fail. ``M`` must be greater than or equal to ``N``. + x0 : ndarray + The starting estimate for the minimization. + args : tuple, optional + Any extra arguments to func are placed in this tuple. + Dfun : callable, optional + A function or method to compute the Jacobian of func with derivatives + across the rows. If this is None, the Jacobian will be estimated. + full_output : bool, optional + If ``True``, return all optional outputs (not just `x` and `ier`). + col_deriv : bool, optional + If ``True``, specify that the Jacobian function computes derivatives + down the columns (faster, because there is no transpose operation). + ftol : float, optional + Relative error desired in the sum of squares. + xtol : float, optional + Relative error desired in the approximate solution. + gtol : float, optional + Orthogonality desired between the function vector and the columns of + the Jacobian. + maxfev : int, optional + The maximum number of calls to the function. If `Dfun` is provided, + then the default `maxfev` is 100*(N+1) where N is the number of elements + in x0, otherwise the default `maxfev` is 200*(N+1). + epsfcn : float, optional + A variable used in determining a suitable step length for the forward- + difference approximation of the Jacobian (for Dfun=None). + Normally the actual step length will be sqrt(epsfcn)*x + If epsfcn is less than the machine precision, it is assumed that the + relative errors are of the order of the machine precision. + factor : float, optional + A parameter determining the initial step bound + (``factor * || diag * x||``). Should be in interval ``(0.1, 100)``. + diag : sequence, optional + N positive entries that serve as a scale factors for the variables. + + Returns + ------- + x : ndarray + The solution (or the result of the last iteration for an unsuccessful + call). + cov_x : ndarray + The inverse of the Hessian. `fjac` and `ipvt` are used to construct an + estimate of the Hessian. A value of None indicates a singular matrix, + which means the curvature in parameters `x` is numerically flat. To + obtain the covariance matrix of the parameters `x`, `cov_x` must be + multiplied by the variance of the residuals -- see curve_fit. Only + returned if `full_output` is ``True``. + infodict : dict + a dictionary of optional outputs with the keys: + + ``nfev`` + The number of function calls + ``fvec`` + The function evaluated at the output + ``fjac`` + A permutation of the R matrix of a QR + factorization of the final approximate + Jacobian matrix, stored column wise. + Together with ipvt, the covariance of the + estimate can be approximated. + ``ipvt`` + An integer array of length N which defines + a permutation matrix, p, such that + fjac*p = q*r, where r is upper triangular + with diagonal elements of nonincreasing + magnitude. Column j of p is column ipvt(j) + of the identity matrix. + ``qtf`` + The vector (transpose(q) * fvec). + + Only returned if `full_output` is ``True``. + mesg : str + A string message giving information about the cause of failure. + Only returned if `full_output` is ``True``. + ier : int + An integer flag. If it is equal to 1, 2, 3 or 4, the solution was + found. Otherwise, the solution was not found. In either case, the + optional output variable 'mesg' gives more information. + + See Also + -------- + least_squares : Newer interface to solve nonlinear least-squares problems + with bounds on the variables. See ``method='lm'`` in particular. + + Notes + ----- + "leastsq" is a wrapper around MINPACK's lmdif and lmder algorithms. + + cov_x is a Jacobian approximation to the Hessian of the least squares + objective function. + This approximation assumes that the objective function is based on the + difference between some observed target data (ydata) and a (non-linear) + function of the parameters `f(xdata, params)` :: + + func(params) = ydata - f(xdata, params) + + so that the objective function is :: + + min sum((ydata - f(xdata, params))**2, axis=0) + params + + The solution, `x`, is always a 1-D array, regardless of the shape of `x0`, + or whether `x0` is a scalar. + + Examples + -------- + >>> from scipy.optimize import leastsq + >>> def func(x): + ... return 2*(x-3)**2+1 + >>> leastsq(func, 0) + (array([2.99999999]), 1) + + """ + x0 = asarray(x0).flatten() + n = len(x0) + if not isinstance(args, tuple): + args = (args,) + shape, dtype = _check_func('leastsq', 'func', func, x0, args, n) + m = shape[0] + + if n > m: + raise TypeError(f"Improper input: func input vector length N={n} must" + f" not exceed func output vector length M={m}") + + if epsfcn is None: + epsfcn = finfo(dtype).eps + + if Dfun is None: + if maxfev == 0: + maxfev = 200*(n + 1) + retval = _minpack._lmdif(func, x0, args, full_output, ftol, xtol, + gtol, maxfev, epsfcn, factor, diag) + else: + if col_deriv: + _check_func('leastsq', 'Dfun', Dfun, x0, args, n, (n, m)) + else: + _check_func('leastsq', 'Dfun', Dfun, x0, args, n, (m, n)) + if maxfev == 0: + maxfev = 100 * (n + 1) + retval = _minpack._lmder(func, Dfun, x0, args, full_output, + col_deriv, ftol, xtol, gtol, maxfev, + factor, diag) + + errors = {0: ["Improper input parameters.", TypeError], + 1: ["Both actual and predicted relative reductions " + "in the sum of squares\n are at most %f" % ftol, None], + 2: ["The relative error between two consecutive " + "iterates is at most %f" % xtol, None], + 3: ["Both actual and predicted relative reductions in " + f"the sum of squares\n are at most {ftol:f} and the " + "relative error between two consecutive " + f"iterates is at \n most {xtol:f}", None], + 4: ["The cosine of the angle between func(x) and any " + "column of the\n Jacobian is at most %f in " + "absolute value" % gtol, None], + 5: ["Number of calls to function has reached " + "maxfev = %d." % maxfev, ValueError], + 6: ["ftol=%f is too small, no further reduction " + "in the sum of squares\n is possible." % ftol, + ValueError], + 7: ["xtol=%f is too small, no further improvement in " + "the approximate\n solution is possible." % xtol, + ValueError], + 8: ["gtol=%f is too small, func(x) is orthogonal to the " + "columns of\n the Jacobian to machine " + "precision." % gtol, ValueError]} + + # The FORTRAN return value (possible return values are >= 0 and <= 8) + info = retval[-1] + + if full_output: + cov_x = None + if info in LEASTSQ_SUCCESS: + # This was + # perm = take(eye(n), retval[1]['ipvt'] - 1, 0) + # r = triu(transpose(retval[1]['fjac'])[:n, :]) + # R = dot(r, perm) + # cov_x = inv(dot(transpose(R), R)) + # but the explicit dot product was not necessary and sometimes + # the result was not symmetric positive definite. See gh-4555. + perm = retval[1]['ipvt'] - 1 + n = len(perm) + r = triu(transpose(retval[1]['fjac'])[:n, :]) + inv_triu = linalg.get_lapack_funcs('trtri', (r,)) + try: + # inverse of permuted matrix is a permutation of matrix inverse + invR, trtri_info = inv_triu(r) # default: upper, non-unit diag + if trtri_info != 0: # explicit comparison for readability + raise LinAlgError(f'trtri returned info {trtri_info}') + invR[perm] = invR.copy() + cov_x = invR @ invR.T + except (LinAlgError, ValueError): + pass + return (retval[0], cov_x) + retval[1:-1] + (errors[info][0], info) + else: + if info in LEASTSQ_FAILURE: + warnings.warn(errors[info][0], RuntimeWarning, stacklevel=2) + elif info == 0: + raise errors[info][1](errors[info][0]) + return retval[0], info + + +def _lightweight_memoizer(f): + # very shallow memoization to address gh-13670: only remember the first set + # of parameters and corresponding function value, and only attempt to use + # them twice (the number of times the function is evaluated at x0). + def _memoized_func(params): + if _memoized_func.skip_lookup: + return f(params) + + if np.all(_memoized_func.last_params == params): + return _memoized_func.last_val + elif _memoized_func.last_params is not None: + _memoized_func.skip_lookup = True + + val = f(params) + + if _memoized_func.last_params is None: + _memoized_func.last_params = np.copy(params) + _memoized_func.last_val = val + + return val + + _memoized_func.last_params = None + _memoized_func.last_val = None + _memoized_func.skip_lookup = False + return _memoized_func + + +def _wrap_func(func, xdata, ydata, transform): + if transform is None: + def func_wrapped(params): + return func(xdata, *params) - ydata + elif transform.size == 1 or transform.ndim == 1: + def func_wrapped(params): + return transform * (func(xdata, *params) - ydata) + else: + # Chisq = (y - yd)^T C^{-1} (y-yd) + # transform = L such that C = L L^T + # C^{-1} = L^{-T} L^{-1} + # Chisq = (y - yd)^T L^{-T} L^{-1} (y-yd) + # Define (y-yd)' = L^{-1} (y-yd) + # by solving + # L (y-yd)' = (y-yd) + # and minimize (y-yd)'^T (y-yd)' + def func_wrapped(params): + return solve_triangular(transform, func(xdata, *params) - ydata, lower=True) + return func_wrapped + + +def _wrap_jac(jac, xdata, transform): + if transform is None: + def jac_wrapped(params): + return jac(xdata, *params) + elif transform.ndim == 1: + def jac_wrapped(params): + return transform[:, np.newaxis] * np.asarray(jac(xdata, *params)) + else: + def jac_wrapped(params): + return solve_triangular(transform, + np.asarray(jac(xdata, *params)), + lower=True) + return jac_wrapped + + +def _initialize_feasible(lb, ub): + p0 = np.ones_like(lb) + lb_finite = np.isfinite(lb) + ub_finite = np.isfinite(ub) + + mask = lb_finite & ub_finite + p0[mask] = 0.5 * (lb[mask] + ub[mask]) + + mask = lb_finite & ~ub_finite + p0[mask] = lb[mask] + 1 + + mask = ~lb_finite & ub_finite + p0[mask] = ub[mask] - 1 + + return p0 + + +def curve_fit(f, xdata, ydata, p0=None, sigma=None, absolute_sigma=False, + check_finite=None, bounds=(-np.inf, np.inf), method=None, + jac=None, *, full_output=False, nan_policy=None, + **kwargs): + """ + Use non-linear least squares to fit a function, f, to data. + + Assumes ``ydata = f(xdata, *params) + eps``. + + Parameters + ---------- + f : callable + The model function, f(x, ...). It must take the independent + variable as the first argument and the parameters to fit as + separate remaining arguments. + xdata : array_like + The independent variable where the data is measured. + Should usually be an M-length sequence or an (k,M)-shaped array for + functions with k predictors, and each element should be float + convertible if it is an array like object. + ydata : array_like + The dependent data, a length M array - nominally ``f(xdata, ...)``. + p0 : array_like, optional + Initial guess for the parameters (length N). If None, then the + initial values will all be 1 (if the number of parameters for the + function can be determined using introspection, otherwise a + ValueError is raised). + sigma : None or scalar or M-length sequence or MxM array, optional + Determines the uncertainty in `ydata`. If we define residuals as + ``r = ydata - f(xdata, *popt)``, then the interpretation of `sigma` + depends on its number of dimensions: + + - A scalar or 1-D `sigma` should contain values of standard deviations of + errors in `ydata`. In this case, the optimized function is + ``chisq = sum((r / sigma) ** 2)``. + + - A 2-D `sigma` should contain the covariance matrix of + errors in `ydata`. In this case, the optimized function is + ``chisq = r.T @ inv(sigma) @ r``. + + .. versionadded:: 0.19 + + None (default) is equivalent of 1-D `sigma` filled with ones. + absolute_sigma : bool, optional + If True, `sigma` is used in an absolute sense and the estimated parameter + covariance `pcov` reflects these absolute values. + + If False (default), only the relative magnitudes of the `sigma` values matter. + The returned parameter covariance matrix `pcov` is based on scaling + `sigma` by a constant factor. This constant is set by demanding that the + reduced `chisq` for the optimal parameters `popt` when using the + *scaled* `sigma` equals unity. In other words, `sigma` is scaled to + match the sample variance of the residuals after the fit. Default is False. + Mathematically, + ``pcov(absolute_sigma=False) = pcov(absolute_sigma=True) * chisq(popt)/(M-N)`` + check_finite : bool, optional + If True, check that the input arrays do not contain nans of infs, + and raise a ValueError if they do. Setting this parameter to + False may silently produce nonsensical results if the input arrays + do contain nans. Default is True if `nan_policy` is not specified + explicitly and False otherwise. + bounds : 2-tuple of array_like or `Bounds`, optional + Lower and upper bounds on parameters. Defaults to no bounds. + There are two ways to specify the bounds: + + - Instance of `Bounds` class. + + - 2-tuple of array_like: Each element of the tuple must be either + an array with the length equal to the number of parameters, or a + scalar (in which case the bound is taken to be the same for all + parameters). Use ``np.inf`` with an appropriate sign to disable + bounds on all or some parameters. + + method : {'lm', 'trf', 'dogbox'}, optional + Method to use for optimization. See `least_squares` for more details. + Default is 'lm' for unconstrained problems and 'trf' if `bounds` are + provided. The method 'lm' won't work when the number of observations + is less than the number of variables, use 'trf' or 'dogbox' in this + case. + + .. versionadded:: 0.17 + jac : callable, string or None, optional + Function with signature ``jac(x, ...)`` which computes the Jacobian + matrix of the model function with respect to parameters as a dense + array_like structure. It will be scaled according to provided `sigma`. + If None (default), the Jacobian will be estimated numerically. + String keywords for 'trf' and 'dogbox' methods can be used to select + a finite difference scheme, see `least_squares`. + + .. versionadded:: 0.18 + full_output : boolean, optional + If True, this function returns additioal information: `infodict`, + `mesg`, and `ier`. + + .. versionadded:: 1.9 + nan_policy : {'raise', 'omit', None}, optional + Defines how to handle when input contains nan. + The following options are available (default is None): + + * 'raise': throws an error + * 'omit': performs the calculations ignoring nan values + * None: no special handling of NaNs is performed + (except what is done by check_finite); the behavior when NaNs + are present is implementation-dependent and may change. + + Note that if this value is specified explicitly (not None), + `check_finite` will be set as False. + + .. versionadded:: 1.11 + **kwargs + Keyword arguments passed to `leastsq` for ``method='lm'`` or + `least_squares` otherwise. + + Returns + ------- + popt : array + Optimal values for the parameters so that the sum of the squared + residuals of ``f(xdata, *popt) - ydata`` is minimized. + pcov : 2-D array + The estimated approximate covariance of popt. The diagonals provide + the variance of the parameter estimate. To compute one standard + deviation errors on the parameters, use + ``perr = np.sqrt(np.diag(pcov))``. Note that the relationship between + `cov` and parameter error estimates is derived based on a linear + approximation to the model function around the optimum [1]. + When this approximation becomes inaccurate, `cov` may not provide an + accurate measure of uncertainty. + + How the `sigma` parameter affects the estimated covariance + depends on `absolute_sigma` argument, as described above. + + If the Jacobian matrix at the solution doesn't have a full rank, then + 'lm' method returns a matrix filled with ``np.inf``, on the other hand + 'trf' and 'dogbox' methods use Moore-Penrose pseudoinverse to compute + the covariance matrix. Covariance matrices with large condition numbers + (e.g. computed with `numpy.linalg.cond`) may indicate that results are + unreliable. + infodict : dict (returned only if `full_output` is True) + a dictionary of optional outputs with the keys: + + ``nfev`` + The number of function calls. Methods 'trf' and 'dogbox' do not + count function calls for numerical Jacobian approximation, + as opposed to 'lm' method. + ``fvec`` + The residual values evaluated at the solution, for a 1-D `sigma` + this is ``(f(x, *popt) - ydata)/sigma``. + ``fjac`` + A permutation of the R matrix of a QR + factorization of the final approximate + Jacobian matrix, stored column wise. + Together with ipvt, the covariance of the + estimate can be approximated. + Method 'lm' only provides this information. + ``ipvt`` + An integer array of length N which defines + a permutation matrix, p, such that + fjac*p = q*r, where r is upper triangular + with diagonal elements of nonincreasing + magnitude. Column j of p is column ipvt(j) + of the identity matrix. + Method 'lm' only provides this information. + ``qtf`` + The vector (transpose(q) * fvec). + Method 'lm' only provides this information. + + .. versionadded:: 1.9 + mesg : str (returned only if `full_output` is True) + A string message giving information about the solution. + + .. versionadded:: 1.9 + ier : int (returned only if `full_output` is True) + An integer flag. If it is equal to 1, 2, 3 or 4, the solution was + found. Otherwise, the solution was not found. In either case, the + optional output variable `mesg` gives more information. + + .. versionadded:: 1.9 + + Raises + ------ + ValueError + if either `ydata` or `xdata` contain NaNs, or if incompatible options + are used. + + RuntimeError + if the least-squares minimization fails. + + OptimizeWarning + if covariance of the parameters can not be estimated. + + See Also + -------- + least_squares : Minimize the sum of squares of nonlinear functions. + scipy.stats.linregress : Calculate a linear least squares regression for + two sets of measurements. + + Notes + ----- + Users should ensure that inputs `xdata`, `ydata`, and the output of `f` + are ``float64``, or else the optimization may return incorrect results. + + With ``method='lm'``, the algorithm uses the Levenberg-Marquardt algorithm + through `leastsq`. Note that this algorithm can only deal with + unconstrained problems. + + Box constraints can be handled by methods 'trf' and 'dogbox'. Refer to + the docstring of `least_squares` for more information. + + Parameters to be fitted must have similar scale. Differences of multiple + orders of magnitude can lead to incorrect results. For the 'trf' and + 'dogbox' methods, the `x_scale` keyword argument can be used to scale + the parameters. + + References + ---------- + [1] K. Vugrin et al. Confidence region estimation techniques for nonlinear + regression in groundwater flow: Three case studies. Water Resources + Research, Vol. 43, W03423, :doi:`10.1029/2005WR004804` + + Examples + -------- + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy.optimize import curve_fit + + >>> def func(x, a, b, c): + ... return a * np.exp(-b * x) + c + + Define the data to be fit with some noise: + + >>> xdata = np.linspace(0, 4, 50) + >>> y = func(xdata, 2.5, 1.3, 0.5) + >>> rng = np.random.default_rng() + >>> y_noise = 0.2 * rng.normal(size=xdata.size) + >>> ydata = y + y_noise + >>> plt.plot(xdata, ydata, 'b-', label='data') + + Fit for the parameters a, b, c of the function `func`: + + >>> popt, pcov = curve_fit(func, xdata, ydata) + >>> popt + array([2.56274217, 1.37268521, 0.47427475]) + >>> plt.plot(xdata, func(xdata, *popt), 'r-', + ... label='fit: a=%5.3f, b=%5.3f, c=%5.3f' % tuple(popt)) + + Constrain the optimization to the region of ``0 <= a <= 3``, + ``0 <= b <= 1`` and ``0 <= c <= 0.5``: + + >>> popt, pcov = curve_fit(func, xdata, ydata, bounds=(0, [3., 1., 0.5])) + >>> popt + array([2.43736712, 1. , 0.34463856]) + >>> plt.plot(xdata, func(xdata, *popt), 'g--', + ... label='fit: a=%5.3f, b=%5.3f, c=%5.3f' % tuple(popt)) + + >>> plt.xlabel('x') + >>> plt.ylabel('y') + >>> plt.legend() + >>> plt.show() + + For reliable results, the model `func` should not be overparametrized; + redundant parameters can cause unreliable covariance matrices and, in some + cases, poorer quality fits. As a quick check of whether the model may be + overparameterized, calculate the condition number of the covariance matrix: + + >>> np.linalg.cond(pcov) + 34.571092161547405 # may vary + + The value is small, so it does not raise much concern. If, however, we were + to add a fourth parameter ``d`` to `func` with the same effect as ``a``: + + >>> def func2(x, a, b, c, d): + ... return a * d * np.exp(-b * x) + c # a and d are redundant + >>> popt, pcov = curve_fit(func2, xdata, ydata) + >>> np.linalg.cond(pcov) + 1.13250718925596e+32 # may vary + + Such a large value is cause for concern. The diagonal elements of the + covariance matrix, which is related to uncertainty of the fit, gives more + information: + + >>> np.diag(pcov) + array([1.48814742e+29, 3.78596560e-02, 5.39253738e-03, 2.76417220e+28]) # may vary + + Note that the first and last terms are much larger than the other elements, + suggesting that the optimal values of these parameters are ambiguous and + that only one of these parameters is needed in the model. + + If the optimal parameters of `f` differ by multiple orders of magnitude, the + resulting fit can be inaccurate. Sometimes, `curve_fit` can fail to find any + results: + + >>> ydata = func(xdata, 500000, 0.01, 15) + >>> try: + ... popt, pcov = curve_fit(func, xdata, ydata, method = 'trf') + ... except RuntimeError as e: + ... print(e) + Optimal parameters not found: The maximum number of function evaluations is + exceeded. + + If parameter scale is roughly known beforehand, it can be defined in + `x_scale` argument: + + >>> popt, pcov = curve_fit(func, xdata, ydata, method = 'trf', + ... x_scale = [1000, 1, 1]) + >>> popt + array([5.00000000e+05, 1.00000000e-02, 1.49999999e+01]) + """ + if p0 is None: + # determine number of parameters by inspecting the function + sig = _getfullargspec(f) + args = sig.args + if len(args) < 2: + raise ValueError("Unable to determine number of fit parameters.") + n = len(args) - 1 + else: + p0 = np.atleast_1d(p0) + n = p0.size + + if isinstance(bounds, Bounds): + lb, ub = bounds.lb, bounds.ub + else: + lb, ub = prepare_bounds(bounds, n) + if p0 is None: + p0 = _initialize_feasible(lb, ub) + + bounded_problem = np.any((lb > -np.inf) | (ub < np.inf)) + if method is None: + if bounded_problem: + method = 'trf' + else: + method = 'lm' + + if method == 'lm' and bounded_problem: + raise ValueError("Method 'lm' only works for unconstrained problems. " + "Use 'trf' or 'dogbox' instead.") + + if check_finite is None: + check_finite = True if nan_policy is None else False + + # optimization may produce garbage for float32 inputs, cast them to float64 + if check_finite: + ydata = np.asarray_chkfinite(ydata, float) + else: + ydata = np.asarray(ydata, float) + + if isinstance(xdata, (list, tuple, np.ndarray)): + # `xdata` is passed straight to the user-defined `f`, so allow + # non-array_like `xdata`. + if check_finite: + xdata = np.asarray_chkfinite(xdata, float) + else: + xdata = np.asarray(xdata, float) + + if ydata.size == 0: + raise ValueError("`ydata` must not be empty!") + + # nan handling is needed only if check_finite is False because if True, + # the x-y data are already checked, and they don't contain nans. + if not check_finite and nan_policy is not None: + if nan_policy == "propagate": + raise ValueError("`nan_policy='propagate'` is not supported " + "by this function.") + + policies = [None, 'raise', 'omit'] + x_contains_nan, nan_policy = _contains_nan(xdata, nan_policy, + policies=policies) + y_contains_nan, nan_policy = _contains_nan(ydata, nan_policy, + policies=policies) + + if (x_contains_nan or y_contains_nan) and nan_policy == 'omit': + # ignore NaNs for N dimensional arrays + has_nan = np.isnan(xdata) + has_nan = has_nan.any(axis=tuple(range(has_nan.ndim-1))) + has_nan |= np.isnan(ydata) + + xdata = xdata[..., ~has_nan] + ydata = ydata[~has_nan] + + # Determine type of sigma + if sigma is not None: + sigma = np.asarray(sigma) + + # if 1-D or a scalar, sigma are errors, define transform = 1/sigma + if sigma.size == 1 or sigma.shape == (ydata.size, ): + transform = 1.0 / sigma + # if 2-D, sigma is the covariance matrix, + # define transform = L such that L L^T = C + elif sigma.shape == (ydata.size, ydata.size): + try: + # scipy.linalg.cholesky requires lower=True to return L L^T = A + transform = cholesky(sigma, lower=True) + except LinAlgError as e: + raise ValueError("`sigma` must be positive definite.") from e + else: + raise ValueError("`sigma` has incorrect shape.") + else: + transform = None + + func = _lightweight_memoizer(_wrap_func(f, xdata, ydata, transform)) + + if callable(jac): + jac = _lightweight_memoizer(_wrap_jac(jac, xdata, transform)) + elif jac is None and method != 'lm': + jac = '2-point' + + if 'args' in kwargs: + # The specification for the model function `f` does not support + # additional arguments. Refer to the `curve_fit` docstring for + # acceptable call signatures of `f`. + raise ValueError("'args' is not a supported keyword argument.") + + if method == 'lm': + # if ydata.size == 1, this might be used for broadcast. + if ydata.size != 1 and n > ydata.size: + raise TypeError(f"The number of func parameters={n} must not" + f" exceed the number of data points={ydata.size}") + res = leastsq(func, p0, Dfun=jac, full_output=1, **kwargs) + popt, pcov, infodict, errmsg, ier = res + ysize = len(infodict['fvec']) + cost = np.sum(infodict['fvec'] ** 2) + if ier not in [1, 2, 3, 4]: + raise RuntimeError("Optimal parameters not found: " + errmsg) + else: + # Rename maxfev (leastsq) to max_nfev (least_squares), if specified. + if 'max_nfev' not in kwargs: + kwargs['max_nfev'] = kwargs.pop('maxfev', None) + + res = least_squares(func, p0, jac=jac, bounds=bounds, method=method, + **kwargs) + + if not res.success: + raise RuntimeError("Optimal parameters not found: " + res.message) + + infodict = dict(nfev=res.nfev, fvec=res.fun) + ier = res.status + errmsg = res.message + + ysize = len(res.fun) + cost = 2 * res.cost # res.cost is half sum of squares! + popt = res.x + + # Do Moore-Penrose inverse discarding zero singular values. + _, s, VT = svd(res.jac, full_matrices=False) + threshold = np.finfo(float).eps * max(res.jac.shape) * s[0] + s = s[s > threshold] + VT = VT[:s.size] + pcov = np.dot(VT.T / s**2, VT) + + warn_cov = False + if pcov is None or np.isnan(pcov).any(): + # indeterminate covariance + pcov = zeros((len(popt), len(popt)), dtype=float) + pcov.fill(inf) + warn_cov = True + elif not absolute_sigma: + if ysize > p0.size: + s_sq = cost / (ysize - p0.size) + pcov = pcov * s_sq + else: + pcov.fill(inf) + warn_cov = True + + if warn_cov: + warnings.warn('Covariance of the parameters could not be estimated', + category=OptimizeWarning, stacklevel=2) + + if full_output: + return popt, pcov, infodict, errmsg, ier + else: + return popt, pcov + + +def check_gradient(fcn, Dfcn, x0, args=(), col_deriv=0): + """Perform a simple check on the gradient for correctness. + + """ + + x = atleast_1d(x0) + n = len(x) + x = x.reshape((n,)) + fvec = atleast_1d(fcn(x, *args)) + m = len(fvec) + fvec = fvec.reshape((m,)) + ldfjac = m + fjac = atleast_1d(Dfcn(x, *args)) + fjac = fjac.reshape((m, n)) + if col_deriv == 0: + fjac = transpose(fjac) + + xp = zeros((n,), float) + err = zeros((m,), float) + fvecp = None + _minpack._chkder(m, n, x, fvec, fjac, ldfjac, xp, fvecp, 1, err) + + fvecp = atleast_1d(fcn(xp, *args)) + fvecp = fvecp.reshape((m,)) + _minpack._chkder(m, n, x, fvec, fjac, ldfjac, xp, fvecp, 2, err) + + good = (prod(greater(err, 0.5), axis=0)) + + return (good, err) + + +def _del2(p0, p1, d): + return p0 - np.square(p1 - p0) / d + + +def _relerr(actual, desired): + return (actual - desired) / desired + + +def _fixed_point_helper(func, x0, args, xtol, maxiter, use_accel): + p0 = x0 + for i in range(maxiter): + p1 = func(p0, *args) + if use_accel: + p2 = func(p1, *args) + d = p2 - 2.0 * p1 + p0 + p = _lazywhere(d != 0, (p0, p1, d), f=_del2, fillvalue=p2) + else: + p = p1 + relerr = _lazywhere(p0 != 0, (p, p0), f=_relerr, fillvalue=p) + if np.all(np.abs(relerr) < xtol): + return p + p0 = p + msg = "Failed to converge after %d iterations, value is %s" % (maxiter, p) + raise RuntimeError(msg) + + +def fixed_point(func, x0, args=(), xtol=1e-8, maxiter=500, method='del2'): + """ + Find a fixed point of the function. + + Given a function of one or more variables and a starting point, find a + fixed point of the function: i.e., where ``func(x0) == x0``. + + Parameters + ---------- + func : function + Function to evaluate. + x0 : array_like + Fixed point of function. + args : tuple, optional + Extra arguments to `func`. + xtol : float, optional + Convergence tolerance, defaults to 1e-08. + maxiter : int, optional + Maximum number of iterations, defaults to 500. + method : {"del2", "iteration"}, optional + Method of finding the fixed-point, defaults to "del2", + which uses Steffensen's Method with Aitken's ``Del^2`` + convergence acceleration [1]_. The "iteration" method simply iterates + the function until convergence is detected, without attempting to + accelerate the convergence. + + References + ---------- + .. [1] Burden, Faires, "Numerical Analysis", 5th edition, pg. 80 + + Examples + -------- + >>> import numpy as np + >>> from scipy import optimize + >>> def func(x, c1, c2): + ... return np.sqrt(c1/(x+c2)) + >>> c1 = np.array([10,12.]) + >>> c2 = np.array([3, 5.]) + >>> optimize.fixed_point(func, [1.2, 1.3], args=(c1,c2)) + array([ 1.4920333 , 1.37228132]) + + """ + use_accel = {'del2': True, 'iteration': False}[method] + x0 = _asarray_validated(x0, as_inexact=True) + return _fixed_point_helper(func, x0, args, xtol, maxiter, use_accel) diff --git a/llava_next/lib/python3.10/site-packages/scipy/optimize/_moduleTNC.cpython-310-x86_64-linux-gnu.so b/llava_next/lib/python3.10/site-packages/scipy/optimize/_moduleTNC.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..052cf91b5917f4e7484ba340de6273c7f7d00fb0 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/scipy/optimize/_moduleTNC.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d7584b3d74b2c7f2804c049af2291355762236b8a294520a6c7a83085ac11544 +size 152168 diff --git a/llava_next/lib/python3.10/site-packages/scipy/optimize/_nonlin.py b/llava_next/lib/python3.10/site-packages/scipy/optimize/_nonlin.py new file mode 100644 index 0000000000000000000000000000000000000000..cbaa3d4ced448df492e965cffe39e99f593c8895 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/scipy/optimize/_nonlin.py @@ -0,0 +1,1585 @@ +# Copyright (C) 2009, Pauli Virtanen +# Distributed under the same license as SciPy. + +import inspect +import sys +import warnings + +import numpy as np +from numpy import asarray, dot, vdot + +from scipy.linalg import norm, solve, inv, qr, svd, LinAlgError +import scipy.sparse.linalg +import scipy.sparse +from scipy.linalg import get_blas_funcs +from scipy._lib._util import copy_if_needed +from scipy._lib._util import getfullargspec_no_self as _getfullargspec +from ._linesearch import scalar_search_wolfe1, scalar_search_armijo + + +__all__ = [ + 'broyden1', 'broyden2', 'anderson', 'linearmixing', + 'diagbroyden', 'excitingmixing', 'newton_krylov', + 'BroydenFirst', 'KrylovJacobian', 'InverseJacobian', 'NoConvergence'] + +#------------------------------------------------------------------------------ +# Utility functions +#------------------------------------------------------------------------------ + + +class NoConvergence(Exception): + """Exception raised when nonlinear solver fails to converge within the specified + `maxiter`.""" + pass + + +def maxnorm(x): + return np.absolute(x).max() + + +def _as_inexact(x): + """Return `x` as an array, of either floats or complex floats""" + x = asarray(x) + if not np.issubdtype(x.dtype, np.inexact): + return asarray(x, dtype=np.float64) + return x + + +def _array_like(x, x0): + """Return ndarray `x` as same array subclass and shape as `x0`""" + x = np.reshape(x, np.shape(x0)) + wrap = getattr(x0, '__array_wrap__', x.__array_wrap__) + return wrap(x) + + +def _safe_norm(v): + if not np.isfinite(v).all(): + return np.array(np.inf) + return norm(v) + +#------------------------------------------------------------------------------ +# Generic nonlinear solver machinery +#------------------------------------------------------------------------------ + + +_doc_parts = dict( + params_basic=""" + F : function(x) -> f + Function whose root to find; should take and return an array-like + object. + xin : array_like + Initial guess for the solution + """.strip(), + params_extra=""" + iter : int, optional + Number of iterations to make. If omitted (default), make as many + as required to meet tolerances. + verbose : bool, optional + Print status to stdout on every iteration. + maxiter : int, optional + Maximum number of iterations to make. If more are needed to + meet convergence, `NoConvergence` is raised. + f_tol : float, optional + Absolute tolerance (in max-norm) for the residual. + If omitted, default is 6e-6. + f_rtol : float, optional + Relative tolerance for the residual. If omitted, not used. + x_tol : float, optional + Absolute minimum step size, as determined from the Jacobian + approximation. If the step size is smaller than this, optimization + is terminated as successful. If omitted, not used. + x_rtol : float, optional + Relative minimum step size. If omitted, not used. + tol_norm : function(vector) -> scalar, optional + Norm to use in convergence check. Default is the maximum norm. + line_search : {None, 'armijo' (default), 'wolfe'}, optional + Which type of a line search to use to determine the step size in the + direction given by the Jacobian approximation. Defaults to 'armijo'. + callback : function, optional + Optional callback function. It is called on every iteration as + ``callback(x, f)`` where `x` is the current solution and `f` + the corresponding residual. + + Returns + ------- + sol : ndarray + An array (of similar array type as `x0`) containing the final solution. + + Raises + ------ + NoConvergence + When a solution was not found. + + """.strip() +) + + +def _set_doc(obj): + if obj.__doc__: + obj.__doc__ = obj.__doc__ % _doc_parts + + +def nonlin_solve(F, x0, jacobian='krylov', iter=None, verbose=False, + maxiter=None, f_tol=None, f_rtol=None, x_tol=None, x_rtol=None, + tol_norm=None, line_search='armijo', callback=None, + full_output=False, raise_exception=True): + """ + Find a root of a function, in a way suitable for large-scale problems. + + Parameters + ---------- + %(params_basic)s + jacobian : Jacobian + A Jacobian approximation: `Jacobian` object or something that + `asjacobian` can transform to one. Alternatively, a string specifying + which of the builtin Jacobian approximations to use: + + krylov, broyden1, broyden2, anderson + diagbroyden, linearmixing, excitingmixing + + %(params_extra)s + full_output : bool + If true, returns a dictionary `info` containing convergence + information. + raise_exception : bool + If True, a `NoConvergence` exception is raise if no solution is found. + + See Also + -------- + asjacobian, Jacobian + + Notes + ----- + This algorithm implements the inexact Newton method, with + backtracking or full line searches. Several Jacobian + approximations are available, including Krylov and Quasi-Newton + methods. + + References + ---------- + .. [KIM] C. T. Kelley, \"Iterative Methods for Linear and Nonlinear + Equations\". Society for Industrial and Applied Mathematics. (1995) + https://archive.siam.org/books/kelley/fr16/ + + """ + # Can't use default parameters because it's being explicitly passed as None + # from the calling function, so we need to set it here. + tol_norm = maxnorm if tol_norm is None else tol_norm + condition = TerminationCondition(f_tol=f_tol, f_rtol=f_rtol, + x_tol=x_tol, x_rtol=x_rtol, + iter=iter, norm=tol_norm) + + x0 = _as_inexact(x0) + def func(z): + return _as_inexact(F(_array_like(z, x0))).flatten() + x = x0.flatten() + + dx = np.full_like(x, np.inf) + Fx = func(x) + Fx_norm = norm(Fx) + + jacobian = asjacobian(jacobian) + jacobian.setup(x.copy(), Fx, func) + + if maxiter is None: + if iter is not None: + maxiter = iter + 1 + else: + maxiter = 100*(x.size+1) + + if line_search is True: + line_search = 'armijo' + elif line_search is False: + line_search = None + + if line_search not in (None, 'armijo', 'wolfe'): + raise ValueError("Invalid line search") + + # Solver tolerance selection + gamma = 0.9 + eta_max = 0.9999 + eta_treshold = 0.1 + eta = 1e-3 + + for n in range(maxiter): + status = condition.check(Fx, x, dx) + if status: + break + + # The tolerance, as computed for scipy.sparse.linalg.* routines + tol = min(eta, eta*Fx_norm) + dx = -jacobian.solve(Fx, tol=tol) + + if norm(dx) == 0: + raise ValueError("Jacobian inversion yielded zero vector. " + "This indicates a bug in the Jacobian " + "approximation.") + + # Line search, or Newton step + if line_search: + s, x, Fx, Fx_norm_new = _nonlin_line_search(func, x, Fx, dx, + line_search) + else: + s = 1.0 + x = x + dx + Fx = func(x) + Fx_norm_new = norm(Fx) + + jacobian.update(x.copy(), Fx) + + if callback: + callback(x, Fx) + + # Adjust forcing parameters for inexact methods + eta_A = gamma * Fx_norm_new**2 / Fx_norm**2 + if gamma * eta**2 < eta_treshold: + eta = min(eta_max, eta_A) + else: + eta = min(eta_max, max(eta_A, gamma*eta**2)) + + Fx_norm = Fx_norm_new + + # Print status + if verbose: + sys.stdout.write("%d: |F(x)| = %g; step %g\n" % ( + n, tol_norm(Fx), s)) + sys.stdout.flush() + else: + if raise_exception: + raise NoConvergence(_array_like(x, x0)) + else: + status = 2 + + if full_output: + info = {'nit': condition.iteration, + 'fun': Fx, + 'status': status, + 'success': status == 1, + 'message': {1: 'A solution was found at the specified ' + 'tolerance.', + 2: 'The maximum number of iterations allowed ' + 'has been reached.' + }[status] + } + return _array_like(x, x0), info + else: + return _array_like(x, x0) + + +_set_doc(nonlin_solve) + + +def _nonlin_line_search(func, x, Fx, dx, search_type='armijo', rdiff=1e-8, + smin=1e-2): + tmp_s = [0] + tmp_Fx = [Fx] + tmp_phi = [norm(Fx)**2] + s_norm = norm(x) / norm(dx) + + def phi(s, store=True): + if s == tmp_s[0]: + return tmp_phi[0] + xt = x + s*dx + v = func(xt) + p = _safe_norm(v)**2 + if store: + tmp_s[0] = s + tmp_phi[0] = p + tmp_Fx[0] = v + return p + + def derphi(s): + ds = (abs(s) + s_norm + 1) * rdiff + return (phi(s+ds, store=False) - phi(s)) / ds + + if search_type == 'wolfe': + s, phi1, phi0 = scalar_search_wolfe1(phi, derphi, tmp_phi[0], + xtol=1e-2, amin=smin) + elif search_type == 'armijo': + s, phi1 = scalar_search_armijo(phi, tmp_phi[0], -tmp_phi[0], + amin=smin) + + if s is None: + # XXX: No suitable step length found. Take the full Newton step, + # and hope for the best. + s = 1.0 + + x = x + s*dx + if s == tmp_s[0]: + Fx = tmp_Fx[0] + else: + Fx = func(x) + Fx_norm = norm(Fx) + + return s, x, Fx, Fx_norm + + +class TerminationCondition: + """ + Termination condition for an iteration. It is terminated if + + - |F| < f_rtol*|F_0|, AND + - |F| < f_tol + + AND + + - |dx| < x_rtol*|x|, AND + - |dx| < x_tol + + """ + def __init__(self, f_tol=None, f_rtol=None, x_tol=None, x_rtol=None, + iter=None, norm=maxnorm): + + if f_tol is None: + f_tol = np.finfo(np.float64).eps ** (1./3) + if f_rtol is None: + f_rtol = np.inf + if x_tol is None: + x_tol = np.inf + if x_rtol is None: + x_rtol = np.inf + + self.x_tol = x_tol + self.x_rtol = x_rtol + self.f_tol = f_tol + self.f_rtol = f_rtol + + self.norm = norm + + self.iter = iter + + self.f0_norm = None + self.iteration = 0 + + def check(self, f, x, dx): + self.iteration += 1 + f_norm = self.norm(f) + x_norm = self.norm(x) + dx_norm = self.norm(dx) + + if self.f0_norm is None: + self.f0_norm = f_norm + + if f_norm == 0: + return 1 + + if self.iter is not None: + # backwards compatibility with SciPy 0.6.0 + return 2 * (self.iteration > self.iter) + + # NB: condition must succeed for rtol=inf even if norm == 0 + return int((f_norm <= self.f_tol + and f_norm/self.f_rtol <= self.f0_norm) + and (dx_norm <= self.x_tol + and dx_norm/self.x_rtol <= x_norm)) + + +#------------------------------------------------------------------------------ +# Generic Jacobian approximation +#------------------------------------------------------------------------------ + +class Jacobian: + """ + Common interface for Jacobians or Jacobian approximations. + + The optional methods come useful when implementing trust region + etc., algorithms that often require evaluating transposes of the + Jacobian. + + Methods + ------- + solve + Returns J^-1 * v + update + Updates Jacobian to point `x` (where the function has residual `Fx`) + + matvec : optional + Returns J * v + rmatvec : optional + Returns A^H * v + rsolve : optional + Returns A^-H * v + matmat : optional + Returns A * V, where V is a dense matrix with dimensions (N,K). + todense : optional + Form the dense Jacobian matrix. Necessary for dense trust region + algorithms, and useful for testing. + + Attributes + ---------- + shape + Matrix dimensions (M, N) + dtype + Data type of the matrix. + func : callable, optional + Function the Jacobian corresponds to + + """ + + def __init__(self, **kw): + names = ["solve", "update", "matvec", "rmatvec", "rsolve", + "matmat", "todense", "shape", "dtype"] + for name, value in kw.items(): + if name not in names: + raise ValueError("Unknown keyword argument %s" % name) + if value is not None: + setattr(self, name, kw[name]) + + + if hasattr(self, "todense"): + def __array__(self, dtype=None, copy=None): + if dtype is not None: + raise ValueError(f"`dtype` must be None, was {dtype}") + return self.todense() + + def aspreconditioner(self): + return InverseJacobian(self) + + def solve(self, v, tol=0): + raise NotImplementedError + + def update(self, x, F): + pass + + def setup(self, x, F, func): + self.func = func + self.shape = (F.size, x.size) + self.dtype = F.dtype + if self.__class__.setup is Jacobian.setup: + # Call on the first point unless overridden + self.update(x, F) + + +class InverseJacobian: + def __init__(self, jacobian): + self.jacobian = jacobian + self.matvec = jacobian.solve + self.update = jacobian.update + if hasattr(jacobian, 'setup'): + self.setup = jacobian.setup + if hasattr(jacobian, 'rsolve'): + self.rmatvec = jacobian.rsolve + + @property + def shape(self): + return self.jacobian.shape + + @property + def dtype(self): + return self.jacobian.dtype + + +def asjacobian(J): + """ + Convert given object to one suitable for use as a Jacobian. + """ + spsolve = scipy.sparse.linalg.spsolve + if isinstance(J, Jacobian): + return J + elif inspect.isclass(J) and issubclass(J, Jacobian): + return J() + elif isinstance(J, np.ndarray): + if J.ndim > 2: + raise ValueError('array must have rank <= 2') + J = np.atleast_2d(np.asarray(J)) + if J.shape[0] != J.shape[1]: + raise ValueError('array must be square') + + return Jacobian(matvec=lambda v: dot(J, v), + rmatvec=lambda v: dot(J.conj().T, v), + solve=lambda v, tol=0: solve(J, v), + rsolve=lambda v, tol=0: solve(J.conj().T, v), + dtype=J.dtype, shape=J.shape) + elif scipy.sparse.issparse(J): + if J.shape[0] != J.shape[1]: + raise ValueError('matrix must be square') + return Jacobian(matvec=lambda v: J @ v, + rmatvec=lambda v: J.conj().T @ v, + solve=lambda v, tol=0: spsolve(J, v), + rsolve=lambda v, tol=0: spsolve(J.conj().T, v), + dtype=J.dtype, shape=J.shape) + elif hasattr(J, 'shape') and hasattr(J, 'dtype') and hasattr(J, 'solve'): + return Jacobian(matvec=getattr(J, 'matvec'), + rmatvec=getattr(J, 'rmatvec'), + solve=J.solve, + rsolve=getattr(J, 'rsolve'), + update=getattr(J, 'update'), + setup=getattr(J, 'setup'), + dtype=J.dtype, + shape=J.shape) + elif callable(J): + # Assume it's a function J(x) that returns the Jacobian + class Jac(Jacobian): + def update(self, x, F): + self.x = x + + def solve(self, v, tol=0): + m = J(self.x) + if isinstance(m, np.ndarray): + return solve(m, v) + elif scipy.sparse.issparse(m): + return spsolve(m, v) + else: + raise ValueError("Unknown matrix type") + + def matvec(self, v): + m = J(self.x) + if isinstance(m, np.ndarray): + return dot(m, v) + elif scipy.sparse.issparse(m): + return m @ v + else: + raise ValueError("Unknown matrix type") + + def rsolve(self, v, tol=0): + m = J(self.x) + if isinstance(m, np.ndarray): + return solve(m.conj().T, v) + elif scipy.sparse.issparse(m): + return spsolve(m.conj().T, v) + else: + raise ValueError("Unknown matrix type") + + def rmatvec(self, v): + m = J(self.x) + if isinstance(m, np.ndarray): + return dot(m.conj().T, v) + elif scipy.sparse.issparse(m): + return m.conj().T @ v + else: + raise ValueError("Unknown matrix type") + return Jac() + elif isinstance(J, str): + return dict(broyden1=BroydenFirst, + broyden2=BroydenSecond, + anderson=Anderson, + diagbroyden=DiagBroyden, + linearmixing=LinearMixing, + excitingmixing=ExcitingMixing, + krylov=KrylovJacobian)[J]() + else: + raise TypeError('Cannot convert object to a Jacobian') + + +#------------------------------------------------------------------------------ +# Broyden +#------------------------------------------------------------------------------ + +class GenericBroyden(Jacobian): + def setup(self, x0, f0, func): + Jacobian.setup(self, x0, f0, func) + self.last_f = f0 + self.last_x = x0 + + if hasattr(self, 'alpha') and self.alpha is None: + # Autoscale the initial Jacobian parameter + # unless we have already guessed the solution. + normf0 = norm(f0) + if normf0: + self.alpha = 0.5*max(norm(x0), 1) / normf0 + else: + self.alpha = 1.0 + + def _update(self, x, f, dx, df, dx_norm, df_norm): + raise NotImplementedError + + def update(self, x, f): + df = f - self.last_f + dx = x - self.last_x + self._update(x, f, dx, df, norm(dx), norm(df)) + self.last_f = f + self.last_x = x + + +class LowRankMatrix: + r""" + A matrix represented as + + .. math:: \alpha I + \sum_{n=0}^{n=M} c_n d_n^\dagger + + However, if the rank of the matrix reaches the dimension of the vectors, + full matrix representation will be used thereon. + + """ + + def __init__(self, alpha, n, dtype): + self.alpha = alpha + self.cs = [] + self.ds = [] + self.n = n + self.dtype = dtype + self.collapsed = None + + @staticmethod + def _matvec(v, alpha, cs, ds): + axpy, scal, dotc = get_blas_funcs(['axpy', 'scal', 'dotc'], + cs[:1] + [v]) + w = alpha * v + for c, d in zip(cs, ds): + a = dotc(d, v) + w = axpy(c, w, w.size, a) + return w + + @staticmethod + def _solve(v, alpha, cs, ds): + """Evaluate w = M^-1 v""" + if len(cs) == 0: + return v/alpha + + # (B + C D^H)^-1 = B^-1 - B^-1 C (I + D^H B^-1 C)^-1 D^H B^-1 + + axpy, dotc = get_blas_funcs(['axpy', 'dotc'], cs[:1] + [v]) + + c0 = cs[0] + A = alpha * np.identity(len(cs), dtype=c0.dtype) + for i, d in enumerate(ds): + for j, c in enumerate(cs): + A[i,j] += dotc(d, c) + + q = np.zeros(len(cs), dtype=c0.dtype) + for j, d in enumerate(ds): + q[j] = dotc(d, v) + q /= alpha + q = solve(A, q) + + w = v/alpha + for c, qc in zip(cs, q): + w = axpy(c, w, w.size, -qc) + + return w + + def matvec(self, v): + """Evaluate w = M v""" + if self.collapsed is not None: + return np.dot(self.collapsed, v) + return LowRankMatrix._matvec(v, self.alpha, self.cs, self.ds) + + def rmatvec(self, v): + """Evaluate w = M^H v""" + if self.collapsed is not None: + return np.dot(self.collapsed.T.conj(), v) + return LowRankMatrix._matvec(v, np.conj(self.alpha), self.ds, self.cs) + + def solve(self, v, tol=0): + """Evaluate w = M^-1 v""" + if self.collapsed is not None: + return solve(self.collapsed, v) + return LowRankMatrix._solve(v, self.alpha, self.cs, self.ds) + + def rsolve(self, v, tol=0): + """Evaluate w = M^-H v""" + if self.collapsed is not None: + return solve(self.collapsed.T.conj(), v) + return LowRankMatrix._solve(v, np.conj(self.alpha), self.ds, self.cs) + + def append(self, c, d): + if self.collapsed is not None: + self.collapsed += c[:,None] * d[None,:].conj() + return + + self.cs.append(c) + self.ds.append(d) + + if len(self.cs) > c.size: + self.collapse() + + def __array__(self, dtype=None, copy=None): + if dtype is not None: + warnings.warn("LowRankMatrix is scipy-internal code, `dtype` " + f"should only be None but was {dtype} (not handled)", + stacklevel=3) + if copy is not None: + warnings.warn("LowRankMatrix is scipy-internal code, `copy` " + f"should only be None but was {copy} (not handled)", + stacklevel=3) + if self.collapsed is not None: + return self.collapsed + + Gm = self.alpha*np.identity(self.n, dtype=self.dtype) + for c, d in zip(self.cs, self.ds): + Gm += c[:,None]*d[None,:].conj() + return Gm + + def collapse(self): + """Collapse the low-rank matrix to a full-rank one.""" + self.collapsed = np.array(self, copy=copy_if_needed) + self.cs = None + self.ds = None + self.alpha = None + + def restart_reduce(self, rank): + """ + Reduce the rank of the matrix by dropping all vectors. + """ + if self.collapsed is not None: + return + assert rank > 0 + if len(self.cs) > rank: + del self.cs[:] + del self.ds[:] + + def simple_reduce(self, rank): + """ + Reduce the rank of the matrix by dropping oldest vectors. + """ + if self.collapsed is not None: + return + assert rank > 0 + while len(self.cs) > rank: + del self.cs[0] + del self.ds[0] + + def svd_reduce(self, max_rank, to_retain=None): + """ + Reduce the rank of the matrix by retaining some SVD components. + + This corresponds to the \"Broyden Rank Reduction Inverse\" + algorithm described in [1]_. + + Note that the SVD decomposition can be done by solving only a + problem whose size is the effective rank of this matrix, which + is viable even for large problems. + + Parameters + ---------- + max_rank : int + Maximum rank of this matrix after reduction. + to_retain : int, optional + Number of SVD components to retain when reduction is done + (ie. rank > max_rank). Default is ``max_rank - 2``. + + References + ---------- + .. [1] B.A. van der Rotten, PhD thesis, + \"A limited memory Broyden method to solve high-dimensional + systems of nonlinear equations\". Mathematisch Instituut, + Universiteit Leiden, The Netherlands (2003). + + https://web.archive.org/web/20161022015821/http://www.math.leidenuniv.nl/scripties/Rotten.pdf + + """ + if self.collapsed is not None: + return + + p = max_rank + if to_retain is not None: + q = to_retain + else: + q = p - 2 + + if self.cs: + p = min(p, len(self.cs[0])) + q = max(0, min(q, p-1)) + + m = len(self.cs) + if m < p: + # nothing to do + return + + C = np.array(self.cs).T + D = np.array(self.ds).T + + D, R = qr(D, mode='economic') + C = dot(C, R.T.conj()) + + U, S, WH = svd(C, full_matrices=False) + + C = dot(C, inv(WH)) + D = dot(D, WH.T.conj()) + + for k in range(q): + self.cs[k] = C[:,k].copy() + self.ds[k] = D[:,k].copy() + + del self.cs[q:] + del self.ds[q:] + + +_doc_parts['broyden_params'] = """ + alpha : float, optional + Initial guess for the Jacobian is ``(-1/alpha)``. + reduction_method : str or tuple, optional + Method used in ensuring that the rank of the Broyden matrix + stays low. Can either be a string giving the name of the method, + or a tuple of the form ``(method, param1, param2, ...)`` + that gives the name of the method and values for additional parameters. + + Methods available: + + - ``restart``: drop all matrix columns. Has no extra parameters. + - ``simple``: drop oldest matrix column. Has no extra parameters. + - ``svd``: keep only the most significant SVD components. + Takes an extra parameter, ``to_retain``, which determines the + number of SVD components to retain when rank reduction is done. + Default is ``max_rank - 2``. + + max_rank : int, optional + Maximum rank for the Broyden matrix. + Default is infinity (i.e., no rank reduction). + """.strip() + + +class BroydenFirst(GenericBroyden): + r""" + Find a root of a function, using Broyden's first Jacobian approximation. + + This method is also known as \"Broyden's good method\". + + Parameters + ---------- + %(params_basic)s + %(broyden_params)s + %(params_extra)s + + See Also + -------- + root : Interface to root finding algorithms for multivariate + functions. See ``method='broyden1'`` in particular. + + Notes + ----- + This algorithm implements the inverse Jacobian Quasi-Newton update + + .. math:: H_+ = H + (dx - H df) dx^\dagger H / ( dx^\dagger H df) + + which corresponds to Broyden's first Jacobian update + + .. math:: J_+ = J + (df - J dx) dx^\dagger / dx^\dagger dx + + + References + ---------- + .. [1] B.A. van der Rotten, PhD thesis, + \"A limited memory Broyden method to solve high-dimensional + systems of nonlinear equations\". Mathematisch Instituut, + Universiteit Leiden, The Netherlands (2003). + + https://web.archive.org/web/20161022015821/http://www.math.leidenuniv.nl/scripties/Rotten.pdf + + Examples + -------- + The following functions define a system of nonlinear equations + + >>> def fun(x): + ... return [x[0] + 0.5 * (x[0] - x[1])**3 - 1.0, + ... 0.5 * (x[1] - x[0])**3 + x[1]] + + A solution can be obtained as follows. + + >>> from scipy import optimize + >>> sol = optimize.broyden1(fun, [0, 0]) + >>> sol + array([0.84116396, 0.15883641]) + + """ + + def __init__(self, alpha=None, reduction_method='restart', max_rank=None): + GenericBroyden.__init__(self) + self.alpha = alpha + self.Gm = None + + if max_rank is None: + max_rank = np.inf + self.max_rank = max_rank + + if isinstance(reduction_method, str): + reduce_params = () + else: + reduce_params = reduction_method[1:] + reduction_method = reduction_method[0] + reduce_params = (max_rank - 1,) + reduce_params + + if reduction_method == 'svd': + self._reduce = lambda: self.Gm.svd_reduce(*reduce_params) + elif reduction_method == 'simple': + self._reduce = lambda: self.Gm.simple_reduce(*reduce_params) + elif reduction_method == 'restart': + self._reduce = lambda: self.Gm.restart_reduce(*reduce_params) + else: + raise ValueError("Unknown rank reduction method '%s'" % + reduction_method) + + def setup(self, x, F, func): + GenericBroyden.setup(self, x, F, func) + self.Gm = LowRankMatrix(-self.alpha, self.shape[0], self.dtype) + + def todense(self): + return inv(self.Gm) + + def solve(self, f, tol=0): + r = self.Gm.matvec(f) + if not np.isfinite(r).all(): + # singular; reset the Jacobian approximation + self.setup(self.last_x, self.last_f, self.func) + return self.Gm.matvec(f) + return r + + def matvec(self, f): + return self.Gm.solve(f) + + def rsolve(self, f, tol=0): + return self.Gm.rmatvec(f) + + def rmatvec(self, f): + return self.Gm.rsolve(f) + + def _update(self, x, f, dx, df, dx_norm, df_norm): + self._reduce() # reduce first to preserve secant condition + + v = self.Gm.rmatvec(dx) + c = dx - self.Gm.matvec(df) + d = v / vdot(df, v) + + self.Gm.append(c, d) + + +class BroydenSecond(BroydenFirst): + """ + Find a root of a function, using Broyden\'s second Jacobian approximation. + + This method is also known as \"Broyden's bad method\". + + Parameters + ---------- + %(params_basic)s + %(broyden_params)s + %(params_extra)s + + See Also + -------- + root : Interface to root finding algorithms for multivariate + functions. See ``method='broyden2'`` in particular. + + Notes + ----- + This algorithm implements the inverse Jacobian Quasi-Newton update + + .. math:: H_+ = H + (dx - H df) df^\\dagger / ( df^\\dagger df) + + corresponding to Broyden's second method. + + References + ---------- + .. [1] B.A. van der Rotten, PhD thesis, + \"A limited memory Broyden method to solve high-dimensional + systems of nonlinear equations\". Mathematisch Instituut, + Universiteit Leiden, The Netherlands (2003). + + https://web.archive.org/web/20161022015821/http://www.math.leidenuniv.nl/scripties/Rotten.pdf + + Examples + -------- + The following functions define a system of nonlinear equations + + >>> def fun(x): + ... return [x[0] + 0.5 * (x[0] - x[1])**3 - 1.0, + ... 0.5 * (x[1] - x[0])**3 + x[1]] + + A solution can be obtained as follows. + + >>> from scipy import optimize + >>> sol = optimize.broyden2(fun, [0, 0]) + >>> sol + array([0.84116365, 0.15883529]) + + """ + + def _update(self, x, f, dx, df, dx_norm, df_norm): + self._reduce() # reduce first to preserve secant condition + + v = df + c = dx - self.Gm.matvec(df) + d = v / df_norm**2 + self.Gm.append(c, d) + + +#------------------------------------------------------------------------------ +# Broyden-like (restricted memory) +#------------------------------------------------------------------------------ + +class Anderson(GenericBroyden): + """ + Find a root of a function, using (extended) Anderson mixing. + + The Jacobian is formed by for a 'best' solution in the space + spanned by last `M` vectors. As a result, only a MxM matrix + inversions and MxN multiplications are required. [Ey]_ + + Parameters + ---------- + %(params_basic)s + alpha : float, optional + Initial guess for the Jacobian is (-1/alpha). + M : float, optional + Number of previous vectors to retain. Defaults to 5. + w0 : float, optional + Regularization parameter for numerical stability. + Compared to unity, good values of the order of 0.01. + %(params_extra)s + + See Also + -------- + root : Interface to root finding algorithms for multivariate + functions. See ``method='anderson'`` in particular. + + References + ---------- + .. [Ey] V. Eyert, J. Comp. Phys., 124, 271 (1996). + + Examples + -------- + The following functions define a system of nonlinear equations + + >>> def fun(x): + ... return [x[0] + 0.5 * (x[0] - x[1])**3 - 1.0, + ... 0.5 * (x[1] - x[0])**3 + x[1]] + + A solution can be obtained as follows. + + >>> from scipy import optimize + >>> sol = optimize.anderson(fun, [0, 0]) + >>> sol + array([0.84116588, 0.15883789]) + + """ + + # Note: + # + # Anderson method maintains a rank M approximation of the inverse Jacobian, + # + # J^-1 v ~ -v*alpha + (dX + alpha dF) A^-1 dF^H v + # A = W + dF^H dF + # W = w0^2 diag(dF^H dF) + # + # so that for w0 = 0 the secant condition applies for last M iterates, i.e., + # + # J^-1 df_j = dx_j + # + # for all j = 0 ... M-1. + # + # Moreover, (from Sherman-Morrison-Woodbury formula) + # + # J v ~ [ b I - b^2 C (I + b dF^H A^-1 C)^-1 dF^H ] v + # C = (dX + alpha dF) A^-1 + # b = -1/alpha + # + # and after simplification + # + # J v ~ -v/alpha + (dX/alpha + dF) (dF^H dX - alpha W)^-1 dF^H v + # + + def __init__(self, alpha=None, w0=0.01, M=5): + GenericBroyden.__init__(self) + self.alpha = alpha + self.M = M + self.dx = [] + self.df = [] + self.gamma = None + self.w0 = w0 + + def solve(self, f, tol=0): + dx = -self.alpha*f + + n = len(self.dx) + if n == 0: + return dx + + df_f = np.empty(n, dtype=f.dtype) + for k in range(n): + df_f[k] = vdot(self.df[k], f) + + try: + gamma = solve(self.a, df_f) + except LinAlgError: + # singular; reset the Jacobian approximation + del self.dx[:] + del self.df[:] + return dx + + for m in range(n): + dx += gamma[m]*(self.dx[m] + self.alpha*self.df[m]) + return dx + + def matvec(self, f): + dx = -f/self.alpha + + n = len(self.dx) + if n == 0: + return dx + + df_f = np.empty(n, dtype=f.dtype) + for k in range(n): + df_f[k] = vdot(self.df[k], f) + + b = np.empty((n, n), dtype=f.dtype) + for i in range(n): + for j in range(n): + b[i,j] = vdot(self.df[i], self.dx[j]) + if i == j and self.w0 != 0: + b[i,j] -= vdot(self.df[i], self.df[i])*self.w0**2*self.alpha + gamma = solve(b, df_f) + + for m in range(n): + dx += gamma[m]*(self.df[m] + self.dx[m]/self.alpha) + return dx + + def _update(self, x, f, dx, df, dx_norm, df_norm): + if self.M == 0: + return + + self.dx.append(dx) + self.df.append(df) + + while len(self.dx) > self.M: + self.dx.pop(0) + self.df.pop(0) + + n = len(self.dx) + a = np.zeros((n, n), dtype=f.dtype) + + for i in range(n): + for j in range(i, n): + if i == j: + wd = self.w0**2 + else: + wd = 0 + a[i,j] = (1+wd)*vdot(self.df[i], self.df[j]) + + a += np.triu(a, 1).T.conj() + self.a = a + +#------------------------------------------------------------------------------ +# Simple iterations +#------------------------------------------------------------------------------ + + +class DiagBroyden(GenericBroyden): + """ + Find a root of a function, using diagonal Broyden Jacobian approximation. + + The Jacobian approximation is derived from previous iterations, by + retaining only the diagonal of Broyden matrices. + + .. warning:: + + This algorithm may be useful for specific problems, but whether + it will work may depend strongly on the problem. + + Parameters + ---------- + %(params_basic)s + alpha : float, optional + Initial guess for the Jacobian is (-1/alpha). + %(params_extra)s + + See Also + -------- + root : Interface to root finding algorithms for multivariate + functions. See ``method='diagbroyden'`` in particular. + + Examples + -------- + The following functions define a system of nonlinear equations + + >>> def fun(x): + ... return [x[0] + 0.5 * (x[0] - x[1])**3 - 1.0, + ... 0.5 * (x[1] - x[0])**3 + x[1]] + + A solution can be obtained as follows. + + >>> from scipy import optimize + >>> sol = optimize.diagbroyden(fun, [0, 0]) + >>> sol + array([0.84116403, 0.15883384]) + + """ + + def __init__(self, alpha=None): + GenericBroyden.__init__(self) + self.alpha = alpha + + def setup(self, x, F, func): + GenericBroyden.setup(self, x, F, func) + self.d = np.full((self.shape[0],), 1 / self.alpha, dtype=self.dtype) + + def solve(self, f, tol=0): + return -f / self.d + + def matvec(self, f): + return -f * self.d + + def rsolve(self, f, tol=0): + return -f / self.d.conj() + + def rmatvec(self, f): + return -f * self.d.conj() + + def todense(self): + return np.diag(-self.d) + + def _update(self, x, f, dx, df, dx_norm, df_norm): + self.d -= (df + self.d*dx)*dx/dx_norm**2 + + +class LinearMixing(GenericBroyden): + """ + Find a root of a function, using a scalar Jacobian approximation. + + .. warning:: + + This algorithm may be useful for specific problems, but whether + it will work may depend strongly on the problem. + + Parameters + ---------- + %(params_basic)s + alpha : float, optional + The Jacobian approximation is (-1/alpha). + %(params_extra)s + + See Also + -------- + root : Interface to root finding algorithms for multivariate + functions. See ``method='linearmixing'`` in particular. + + """ + + def __init__(self, alpha=None): + GenericBroyden.__init__(self) + self.alpha = alpha + + def solve(self, f, tol=0): + return -f*self.alpha + + def matvec(self, f): + return -f/self.alpha + + def rsolve(self, f, tol=0): + return -f*np.conj(self.alpha) + + def rmatvec(self, f): + return -f/np.conj(self.alpha) + + def todense(self): + return np.diag(np.full(self.shape[0], -1/self.alpha)) + + def _update(self, x, f, dx, df, dx_norm, df_norm): + pass + + +class ExcitingMixing(GenericBroyden): + """ + Find a root of a function, using a tuned diagonal Jacobian approximation. + + The Jacobian matrix is diagonal and is tuned on each iteration. + + .. warning:: + + This algorithm may be useful for specific problems, but whether + it will work may depend strongly on the problem. + + See Also + -------- + root : Interface to root finding algorithms for multivariate + functions. See ``method='excitingmixing'`` in particular. + + Parameters + ---------- + %(params_basic)s + alpha : float, optional + Initial Jacobian approximation is (-1/alpha). + alphamax : float, optional + The entries of the diagonal Jacobian are kept in the range + ``[alpha, alphamax]``. + %(params_extra)s + """ + + def __init__(self, alpha=None, alphamax=1.0): + GenericBroyden.__init__(self) + self.alpha = alpha + self.alphamax = alphamax + self.beta = None + + def setup(self, x, F, func): + GenericBroyden.setup(self, x, F, func) + self.beta = np.full((self.shape[0],), self.alpha, dtype=self.dtype) + + def solve(self, f, tol=0): + return -f*self.beta + + def matvec(self, f): + return -f/self.beta + + def rsolve(self, f, tol=0): + return -f*self.beta.conj() + + def rmatvec(self, f): + return -f/self.beta.conj() + + def todense(self): + return np.diag(-1/self.beta) + + def _update(self, x, f, dx, df, dx_norm, df_norm): + incr = f*self.last_f > 0 + self.beta[incr] += self.alpha + self.beta[~incr] = self.alpha + np.clip(self.beta, 0, self.alphamax, out=self.beta) + + +#------------------------------------------------------------------------------ +# Iterative/Krylov approximated Jacobians +#------------------------------------------------------------------------------ + +class KrylovJacobian(Jacobian): + r""" + Find a root of a function, using Krylov approximation for inverse Jacobian. + + This method is suitable for solving large-scale problems. + + Parameters + ---------- + %(params_basic)s + rdiff : float, optional + Relative step size to use in numerical differentiation. + method : str or callable, optional + Krylov method to use to approximate the Jacobian. Can be a string, + or a function implementing the same interface as the iterative + solvers in `scipy.sparse.linalg`. If a string, needs to be one of: + ``'lgmres'``, ``'gmres'``, ``'bicgstab'``, ``'cgs'``, ``'minres'``, + ``'tfqmr'``. + + The default is `scipy.sparse.linalg.lgmres`. + inner_maxiter : int, optional + Parameter to pass to the "inner" Krylov solver: maximum number of + iterations. Iteration will stop after maxiter steps even if the + specified tolerance has not been achieved. + inner_M : LinearOperator or InverseJacobian + Preconditioner for the inner Krylov iteration. + Note that you can use also inverse Jacobians as (adaptive) + preconditioners. For example, + + >>> from scipy.optimize import BroydenFirst, KrylovJacobian + >>> from scipy.optimize import InverseJacobian + >>> jac = BroydenFirst() + >>> kjac = KrylovJacobian(inner_M=InverseJacobian(jac)) + + If the preconditioner has a method named 'update', it will be called + as ``update(x, f)`` after each nonlinear step, with ``x`` giving + the current point, and ``f`` the current function value. + outer_k : int, optional + Size of the subspace kept across LGMRES nonlinear iterations. + See `scipy.sparse.linalg.lgmres` for details. + inner_kwargs : kwargs + Keyword parameters for the "inner" Krylov solver + (defined with `method`). Parameter names must start with + the `inner_` prefix which will be stripped before passing on + the inner method. See, e.g., `scipy.sparse.linalg.gmres` for details. + %(params_extra)s + + See Also + -------- + root : Interface to root finding algorithms for multivariate + functions. See ``method='krylov'`` in particular. + scipy.sparse.linalg.gmres + scipy.sparse.linalg.lgmres + + Notes + ----- + This function implements a Newton-Krylov solver. The basic idea is + to compute the inverse of the Jacobian with an iterative Krylov + method. These methods require only evaluating the Jacobian-vector + products, which are conveniently approximated by a finite difference: + + .. math:: J v \approx (f(x + \omega*v/|v|) - f(x)) / \omega + + Due to the use of iterative matrix inverses, these methods can + deal with large nonlinear problems. + + SciPy's `scipy.sparse.linalg` module offers a selection of Krylov + solvers to choose from. The default here is `lgmres`, which is a + variant of restarted GMRES iteration that reuses some of the + information obtained in the previous Newton steps to invert + Jacobians in subsequent steps. + + For a review on Newton-Krylov methods, see for example [1]_, + and for the LGMRES sparse inverse method, see [2]_. + + References + ---------- + .. [1] C. T. Kelley, Solving Nonlinear Equations with Newton's Method, + SIAM, pp.57-83, 2003. + :doi:`10.1137/1.9780898718898.ch3` + .. [2] D.A. Knoll and D.E. Keyes, J. Comp. Phys. 193, 357 (2004). + :doi:`10.1016/j.jcp.2003.08.010` + .. [3] A.H. Baker and E.R. Jessup and T. Manteuffel, + SIAM J. Matrix Anal. Appl. 26, 962 (2005). + :doi:`10.1137/S0895479803422014` + + Examples + -------- + The following functions define a system of nonlinear equations + + >>> def fun(x): + ... return [x[0] + 0.5 * x[1] - 1.0, + ... 0.5 * (x[1] - x[0]) ** 2] + + A solution can be obtained as follows. + + >>> from scipy import optimize + >>> sol = optimize.newton_krylov(fun, [0, 0]) + >>> sol + array([0.66731771, 0.66536458]) + + """ + + def __init__(self, rdiff=None, method='lgmres', inner_maxiter=20, + inner_M=None, outer_k=10, **kw): + self.preconditioner = inner_M + self.rdiff = rdiff + # Note that this retrieves one of the named functions, or otherwise + # uses `method` as is (i.e., for a user-provided callable). + self.method = dict( + bicgstab=scipy.sparse.linalg.bicgstab, + gmres=scipy.sparse.linalg.gmres, + lgmres=scipy.sparse.linalg.lgmres, + cgs=scipy.sparse.linalg.cgs, + minres=scipy.sparse.linalg.minres, + tfqmr=scipy.sparse.linalg.tfqmr, + ).get(method, method) + + self.method_kw = dict(maxiter=inner_maxiter, M=self.preconditioner) + + if self.method is scipy.sparse.linalg.gmres: + # Replace GMRES's outer iteration with Newton steps + self.method_kw['restart'] = inner_maxiter + self.method_kw['maxiter'] = 1 + self.method_kw.setdefault('atol', 0) + elif self.method in (scipy.sparse.linalg.gcrotmk, + scipy.sparse.linalg.bicgstab, + scipy.sparse.linalg.cgs): + self.method_kw.setdefault('atol', 0) + elif self.method is scipy.sparse.linalg.lgmres: + self.method_kw['outer_k'] = outer_k + # Replace LGMRES's outer iteration with Newton steps + self.method_kw['maxiter'] = 1 + # Carry LGMRES's `outer_v` vectors across nonlinear iterations + self.method_kw.setdefault('outer_v', []) + self.method_kw.setdefault('prepend_outer_v', True) + # But don't carry the corresponding Jacobian*v products, in case + # the Jacobian changes a lot in the nonlinear step + # + # XXX: some trust-region inspired ideas might be more efficient... + # See e.g., Brown & Saad. But needs to be implemented separately + # since it's not an inexact Newton method. + self.method_kw.setdefault('store_outer_Av', False) + self.method_kw.setdefault('atol', 0) + + for key, value in kw.items(): + if not key.startswith('inner_'): + raise ValueError("Unknown parameter %s" % key) + self.method_kw[key[6:]] = value + + def _update_diff_step(self): + mx = abs(self.x0).max() + mf = abs(self.f0).max() + self.omega = self.rdiff * max(1, mx) / max(1, mf) + + def matvec(self, v): + nv = norm(v) + if nv == 0: + return 0*v + sc = self.omega / nv + r = (self.func(self.x0 + sc*v) - self.f0) / sc + if not np.all(np.isfinite(r)) and np.all(np.isfinite(v)): + raise ValueError('Function returned non-finite results') + return r + + def solve(self, rhs, tol=0): + if 'rtol' in self.method_kw: + sol, info = self.method(self.op, rhs, **self.method_kw) + else: + sol, info = self.method(self.op, rhs, rtol=tol, **self.method_kw) + return sol + + def update(self, x, f): + self.x0 = x + self.f0 = f + self._update_diff_step() + + # Update also the preconditioner, if possible + if self.preconditioner is not None: + if hasattr(self.preconditioner, 'update'): + self.preconditioner.update(x, f) + + def setup(self, x, f, func): + Jacobian.setup(self, x, f, func) + self.x0 = x + self.f0 = f + self.op = scipy.sparse.linalg.aslinearoperator(self) + + if self.rdiff is None: + self.rdiff = np.finfo(x.dtype).eps ** (1./2) + + self._update_diff_step() + + # Setup also the preconditioner, if possible + if self.preconditioner is not None: + if hasattr(self.preconditioner, 'setup'): + self.preconditioner.setup(x, f, func) + + +#------------------------------------------------------------------------------ +# Wrapper functions +#------------------------------------------------------------------------------ + +def _nonlin_wrapper(name, jac): + """ + Construct a solver wrapper with given name and Jacobian approx. + + It inspects the keyword arguments of ``jac.__init__``, and allows to + use the same arguments in the wrapper function, in addition to the + keyword arguments of `nonlin_solve` + + """ + signature = _getfullargspec(jac.__init__) + args, varargs, varkw, defaults, kwonlyargs, kwdefaults, _ = signature + kwargs = list(zip(args[-len(defaults):], defaults)) + kw_str = ", ".join([f"{k}={v!r}" for k, v in kwargs]) + if kw_str: + kw_str = ", " + kw_str + kwkw_str = ", ".join([f"{k}={k}" for k, v in kwargs]) + if kwkw_str: + kwkw_str = kwkw_str + ", " + if kwonlyargs: + raise ValueError('Unexpected signature %s' % signature) + + # Construct the wrapper function so that its keyword arguments + # are visible in pydoc.help etc. + wrapper = """ +def %(name)s(F, xin, iter=None %(kw)s, verbose=False, maxiter=None, + f_tol=None, f_rtol=None, x_tol=None, x_rtol=None, + tol_norm=None, line_search='armijo', callback=None, **kw): + jac = %(jac)s(%(kwkw)s **kw) + return nonlin_solve(F, xin, jac, iter, verbose, maxiter, + f_tol, f_rtol, x_tol, x_rtol, tol_norm, line_search, + callback) +""" + + wrapper = wrapper % dict(name=name, kw=kw_str, jac=jac.__name__, + kwkw=kwkw_str) + ns = {} + ns.update(globals()) + exec(wrapper, ns) + func = ns[name] + func.__doc__ = jac.__doc__ + _set_doc(func) + return func + + +broyden1 = _nonlin_wrapper('broyden1', BroydenFirst) +broyden2 = _nonlin_wrapper('broyden2', BroydenSecond) +anderson = _nonlin_wrapper('anderson', Anderson) +linearmixing = _nonlin_wrapper('linearmixing', LinearMixing) +diagbroyden = _nonlin_wrapper('diagbroyden', DiagBroyden) +excitingmixing = _nonlin_wrapper('excitingmixing', ExcitingMixing) +newton_krylov = _nonlin_wrapper('newton_krylov', KrylovJacobian) diff --git a/llava_next/lib/python3.10/site-packages/scipy/optimize/_qap.py b/llava_next/lib/python3.10/site-packages/scipy/optimize/_qap.py new file mode 100644 index 0000000000000000000000000000000000000000..094119c0ad6c1e4bba72978390c7273f10ac7fff --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/scipy/optimize/_qap.py @@ -0,0 +1,731 @@ +import numpy as np +import operator +from . import (linear_sum_assignment, OptimizeResult) +from ._optimize import _check_unknown_options + +from scipy._lib._util import check_random_state +import itertools + +QUADRATIC_ASSIGNMENT_METHODS = ['faq', '2opt'] + +def quadratic_assignment(A, B, method="faq", options=None): + r""" + Approximates solution to the quadratic assignment problem and + the graph matching problem. + + Quadratic assignment solves problems of the following form: + + .. math:: + + \min_P & \ {\ \text{trace}(A^T P B P^T)}\\ + \mbox{s.t. } & {P \ \epsilon \ \mathcal{P}}\\ + + where :math:`\mathcal{P}` is the set of all permutation matrices, + and :math:`A` and :math:`B` are square matrices. + + Graph matching tries to *maximize* the same objective function. + This algorithm can be thought of as finding the alignment of the + nodes of two graphs that minimizes the number of induced edge + disagreements, or, in the case of weighted graphs, the sum of squared + edge weight differences. + + Note that the quadratic assignment problem is NP-hard. The results given + here are approximations and are not guaranteed to be optimal. + + + Parameters + ---------- + A : 2-D array, square + The square matrix :math:`A` in the objective function above. + + B : 2-D array, square + The square matrix :math:`B` in the objective function above. + + method : str in {'faq', '2opt'} (default: 'faq') + The algorithm used to solve the problem. + :ref:`'faq' ` (default) and + :ref:`'2opt' ` are available. + + options : dict, optional + A dictionary of solver options. All solvers support the following: + + maximize : bool (default: False) + Maximizes the objective function if ``True``. + + partial_match : 2-D array of integers, optional (default: None) + Fixes part of the matching. Also known as a "seed" [2]_. + + Each row of `partial_match` specifies a pair of matched nodes: + node ``partial_match[i, 0]`` of `A` is matched to node + ``partial_match[i, 1]`` of `B`. The array has shape ``(m, 2)``, + where ``m`` is not greater than the number of nodes, :math:`n`. + + rng : {None, int, `numpy.random.Generator`, + `numpy.random.RandomState`}, optional + + If `seed` is None (or `np.random`), the `numpy.random.RandomState` + singleton is used. + If `seed` is an int, a new ``RandomState`` instance is used, + seeded with `seed`. + If `seed` is already a ``Generator`` or ``RandomState`` instance then + that instance is used. + + For method-specific options, see + :func:`show_options('quadratic_assignment') `. + + Returns + ------- + res : OptimizeResult + `OptimizeResult` containing the following fields. + + col_ind : 1-D array + Column indices corresponding to the best permutation found of the + nodes of `B`. + fun : float + The objective value of the solution. + nit : int + The number of iterations performed during optimization. + + Notes + ----- + The default method :ref:`'faq' ` uses the Fast + Approximate QAP algorithm [1]_; it typically offers the best combination of + speed and accuracy. + Method :ref:`'2opt' ` can be computationally expensive, + but may be a useful alternative, or it can be used to refine the solution + returned by another method. + + References + ---------- + .. [1] J.T. Vogelstein, J.M. Conroy, V. Lyzinski, L.J. Podrazik, + S.G. Kratzer, E.T. Harley, D.E. Fishkind, R.J. Vogelstein, and + C.E. Priebe, "Fast approximate quadratic programming for graph + matching," PLOS one, vol. 10, no. 4, p. e0121002, 2015, + :doi:`10.1371/journal.pone.0121002` + + .. [2] D. Fishkind, S. Adali, H. Patsolic, L. Meng, D. Singh, V. Lyzinski, + C. Priebe, "Seeded graph matching", Pattern Recognit. 87 (2019): + 203-215, :doi:`10.1016/j.patcog.2018.09.014` + + .. [3] "2-opt," Wikipedia. + https://en.wikipedia.org/wiki/2-opt + + Examples + -------- + >>> import numpy as np + >>> from scipy.optimize import quadratic_assignment + >>> A = np.array([[0, 80, 150, 170], [80, 0, 130, 100], + ... [150, 130, 0, 120], [170, 100, 120, 0]]) + >>> B = np.array([[0, 5, 2, 7], [0, 0, 3, 8], + ... [0, 0, 0, 3], [0, 0, 0, 0]]) + >>> res = quadratic_assignment(A, B) + >>> print(res) + fun: 3260 + col_ind: [0 3 2 1] + nit: 9 + + The see the relationship between the returned ``col_ind`` and ``fun``, + use ``col_ind`` to form the best permutation matrix found, then evaluate + the objective function :math:`f(P) = trace(A^T P B P^T )`. + + >>> perm = res['col_ind'] + >>> P = np.eye(len(A), dtype=int)[perm] + >>> fun = np.trace(A.T @ P @ B @ P.T) + >>> print(fun) + 3260 + + Alternatively, to avoid constructing the permutation matrix explicitly, + directly permute the rows and columns of the distance matrix. + + >>> fun = np.trace(A.T @ B[perm][:, perm]) + >>> print(fun) + 3260 + + Although not guaranteed in general, ``quadratic_assignment`` happens to + have found the globally optimal solution. + + >>> from itertools import permutations + >>> perm_opt, fun_opt = None, np.inf + >>> for perm in permutations([0, 1, 2, 3]): + ... perm = np.array(perm) + ... fun = np.trace(A.T @ B[perm][:, perm]) + ... if fun < fun_opt: + ... fun_opt, perm_opt = fun, perm + >>> print(np.array_equal(perm_opt, res['col_ind'])) + True + + Here is an example for which the default method, + :ref:`'faq' `, does not find the global optimum. + + >>> A = np.array([[0, 5, 8, 6], [5, 0, 5, 1], + ... [8, 5, 0, 2], [6, 1, 2, 0]]) + >>> B = np.array([[0, 1, 8, 4], [1, 0, 5, 2], + ... [8, 5, 0, 5], [4, 2, 5, 0]]) + >>> res = quadratic_assignment(A, B) + >>> print(res) + fun: 178 + col_ind: [1 0 3 2] + nit: 13 + + If accuracy is important, consider using :ref:`'2opt' ` + to refine the solution. + + >>> guess = np.array([np.arange(len(A)), res.col_ind]).T + >>> res = quadratic_assignment(A, B, method="2opt", + ... options = {'partial_guess': guess}) + >>> print(res) + fun: 176 + col_ind: [1 2 3 0] + nit: 17 + + """ + + if options is None: + options = {} + + method = method.lower() + methods = {"faq": _quadratic_assignment_faq, + "2opt": _quadratic_assignment_2opt} + if method not in methods: + raise ValueError(f"method {method} must be in {methods}.") + res = methods[method](A, B, **options) + return res + + +def _calc_score(A, B, perm): + # equivalent to objective function but avoids matmul + return np.sum(A * B[perm][:, perm]) + + +def _common_input_validation(A, B, partial_match): + A = np.atleast_2d(A) + B = np.atleast_2d(B) + + if partial_match is None: + partial_match = np.array([[], []]).T + partial_match = np.atleast_2d(partial_match).astype(int) + + msg = None + if A.shape[0] != A.shape[1]: + msg = "`A` must be square" + elif B.shape[0] != B.shape[1]: + msg = "`B` must be square" + elif A.ndim != 2 or B.ndim != 2: + msg = "`A` and `B` must have exactly two dimensions" + elif A.shape != B.shape: + msg = "`A` and `B` matrices must be of equal size" + elif partial_match.shape[0] > A.shape[0]: + msg = "`partial_match` can have only as many seeds as there are nodes" + elif partial_match.shape[1] != 2: + msg = "`partial_match` must have two columns" + elif partial_match.ndim != 2: + msg = "`partial_match` must have exactly two dimensions" + elif (partial_match < 0).any(): + msg = "`partial_match` must contain only positive indices" + elif (partial_match >= len(A)).any(): + msg = "`partial_match` entries must be less than number of nodes" + elif (not len(set(partial_match[:, 0])) == len(partial_match[:, 0]) or + not len(set(partial_match[:, 1])) == len(partial_match[:, 1])): + msg = "`partial_match` column entries must be unique" + + if msg is not None: + raise ValueError(msg) + + return A, B, partial_match + + +def _quadratic_assignment_faq(A, B, + maximize=False, partial_match=None, rng=None, + P0="barycenter", shuffle_input=False, maxiter=30, + tol=0.03, **unknown_options): + r"""Solve the quadratic assignment problem (approximately). + + This function solves the Quadratic Assignment Problem (QAP) and the + Graph Matching Problem (GMP) using the Fast Approximate QAP Algorithm + (FAQ) [1]_. + + Quadratic assignment solves problems of the following form: + + .. math:: + + \min_P & \ {\ \text{trace}(A^T P B P^T)}\\ + \mbox{s.t. } & {P \ \epsilon \ \mathcal{P}}\\ + + where :math:`\mathcal{P}` is the set of all permutation matrices, + and :math:`A` and :math:`B` are square matrices. + + Graph matching tries to *maximize* the same objective function. + This algorithm can be thought of as finding the alignment of the + nodes of two graphs that minimizes the number of induced edge + disagreements, or, in the case of weighted graphs, the sum of squared + edge weight differences. + + Note that the quadratic assignment problem is NP-hard. The results given + here are approximations and are not guaranteed to be optimal. + + Parameters + ---------- + A : 2-D array, square + The square matrix :math:`A` in the objective function above. + B : 2-D array, square + The square matrix :math:`B` in the objective function above. + method : str in {'faq', '2opt'} (default: 'faq') + The algorithm used to solve the problem. This is the method-specific + documentation for 'faq'. + :ref:`'2opt' ` is also available. + + Options + ------- + maximize : bool (default: False) + Maximizes the objective function if ``True``. + partial_match : 2-D array of integers, optional (default: None) + Fixes part of the matching. Also known as a "seed" [2]_. + + Each row of `partial_match` specifies a pair of matched nodes: + node ``partial_match[i, 0]`` of `A` is matched to node + ``partial_match[i, 1]`` of `B`. The array has shape ``(m, 2)``, where + ``m`` is not greater than the number of nodes, :math:`n`. + + rng : {None, int, `numpy.random.Generator`, + `numpy.random.RandomState`}, optional + + If `seed` is None (or `np.random`), the `numpy.random.RandomState` + singleton is used. + If `seed` is an int, a new ``RandomState`` instance is used, + seeded with `seed`. + If `seed` is already a ``Generator`` or ``RandomState`` instance then + that instance is used. + P0 : 2-D array, "barycenter", or "randomized" (default: "barycenter") + Initial position. Must be a doubly-stochastic matrix [3]_. + + If the initial position is an array, it must be a doubly stochastic + matrix of size :math:`m' \times m'` where :math:`m' = n - m`. + + If ``"barycenter"`` (default), the initial position is the barycenter + of the Birkhoff polytope (the space of doubly stochastic matrices). + This is a :math:`m' \times m'` matrix with all entries equal to + :math:`1 / m'`. + + If ``"randomized"`` the initial search position is + :math:`P_0 = (J + K) / 2`, where :math:`J` is the barycenter and + :math:`K` is a random doubly stochastic matrix. + shuffle_input : bool (default: False) + Set to `True` to resolve degenerate gradients randomly. For + non-degenerate gradients this option has no effect. + maxiter : int, positive (default: 30) + Integer specifying the max number of Frank-Wolfe iterations performed. + tol : float (default: 0.03) + Tolerance for termination. Frank-Wolfe iteration terminates when + :math:`\frac{||P_{i}-P_{i+1}||_F}{\sqrt{m')}} \leq tol`, + where :math:`i` is the iteration number. + + Returns + ------- + res : OptimizeResult + `OptimizeResult` containing the following fields. + + col_ind : 1-D array + Column indices corresponding to the best permutation found of the + nodes of `B`. + fun : float + The objective value of the solution. + nit : int + The number of Frank-Wolfe iterations performed. + + Notes + ----- + The algorithm may be sensitive to the initial permutation matrix (or + search "position") due to the possibility of several local minima + within the feasible region. A barycenter initialization is more likely to + result in a better solution than a single random initialization. However, + calling ``quadratic_assignment`` several times with different random + initializations may result in a better optimum at the cost of longer + total execution time. + + Examples + -------- + As mentioned above, a barycenter initialization often results in a better + solution than a single random initialization. + + >>> from numpy.random import default_rng + >>> rng = default_rng() + >>> n = 15 + >>> A = rng.random((n, n)) + >>> B = rng.random((n, n)) + >>> res = quadratic_assignment(A, B) # FAQ is default method + >>> print(res.fun) + 46.871483385480545 # may vary + + >>> options = {"P0": "randomized"} # use randomized initialization + >>> res = quadratic_assignment(A, B, options=options) + >>> print(res.fun) + 47.224831071310625 # may vary + + However, consider running from several randomized initializations and + keeping the best result. + + >>> res = min([quadratic_assignment(A, B, options=options) + ... for i in range(30)], key=lambda x: x.fun) + >>> print(res.fun) + 46.671852533681516 # may vary + + The '2-opt' method can be used to further refine the results. + + >>> options = {"partial_guess": np.array([np.arange(n), res.col_ind]).T} + >>> res = quadratic_assignment(A, B, method="2opt", options=options) + >>> print(res.fun) + 46.47160735721583 # may vary + + References + ---------- + .. [1] J.T. Vogelstein, J.M. Conroy, V. Lyzinski, L.J. Podrazik, + S.G. Kratzer, E.T. Harley, D.E. Fishkind, R.J. Vogelstein, and + C.E. Priebe, "Fast approximate quadratic programming for graph + matching," PLOS one, vol. 10, no. 4, p. e0121002, 2015, + :doi:`10.1371/journal.pone.0121002` + + .. [2] D. Fishkind, S. Adali, H. Patsolic, L. Meng, D. Singh, V. Lyzinski, + C. Priebe, "Seeded graph matching", Pattern Recognit. 87 (2019): + 203-215, :doi:`10.1016/j.patcog.2018.09.014` + + .. [3] "Doubly stochastic Matrix," Wikipedia. + https://en.wikipedia.org/wiki/Doubly_stochastic_matrix + + """ + + _check_unknown_options(unknown_options) + + maxiter = operator.index(maxiter) + + # ValueError check + A, B, partial_match = _common_input_validation(A, B, partial_match) + + msg = None + if isinstance(P0, str) and P0 not in {'barycenter', 'randomized'}: + msg = "Invalid 'P0' parameter string" + elif maxiter <= 0: + msg = "'maxiter' must be a positive integer" + elif tol <= 0: + msg = "'tol' must be a positive float" + if msg is not None: + raise ValueError(msg) + + rng = check_random_state(rng) + n = len(A) # number of vertices in graphs + n_seeds = len(partial_match) # number of seeds + n_unseed = n - n_seeds + + # [1] Algorithm 1 Line 1 - choose initialization + if not isinstance(P0, str): + P0 = np.atleast_2d(P0) + if P0.shape != (n_unseed, n_unseed): + msg = "`P0` matrix must have shape m' x m', where m'=n-m" + elif ((P0 < 0).any() or not np.allclose(np.sum(P0, axis=0), 1) + or not np.allclose(np.sum(P0, axis=1), 1)): + msg = "`P0` matrix must be doubly stochastic" + if msg is not None: + raise ValueError(msg) + elif P0 == 'barycenter': + P0 = np.ones((n_unseed, n_unseed)) / n_unseed + elif P0 == 'randomized': + J = np.ones((n_unseed, n_unseed)) / n_unseed + # generate a nxn matrix where each entry is a random number [0, 1] + # would use rand, but Generators don't have it + # would use random, but old mtrand.RandomStates don't have it + K = _doubly_stochastic(rng.uniform(size=(n_unseed, n_unseed))) + P0 = (J + K) / 2 + + # check trivial cases + if n == 0 or n_seeds == n: + score = _calc_score(A, B, partial_match[:, 1]) + res = {"col_ind": partial_match[:, 1], "fun": score, "nit": 0} + return OptimizeResult(res) + + obj_func_scalar = 1 + if maximize: + obj_func_scalar = -1 + + nonseed_B = np.setdiff1d(range(n), partial_match[:, 1]) + if shuffle_input: + nonseed_B = rng.permutation(nonseed_B) + + nonseed_A = np.setdiff1d(range(n), partial_match[:, 0]) + perm_A = np.concatenate([partial_match[:, 0], nonseed_A]) + perm_B = np.concatenate([partial_match[:, 1], nonseed_B]) + + # definitions according to Seeded Graph Matching [2]. + A11, A12, A21, A22 = _split_matrix(A[perm_A][:, perm_A], n_seeds) + B11, B12, B21, B22 = _split_matrix(B[perm_B][:, perm_B], n_seeds) + const_sum = A21 @ B21.T + A12.T @ B12 + + P = P0 + # [1] Algorithm 1 Line 2 - loop while stopping criteria not met + for n_iter in range(1, maxiter+1): + # [1] Algorithm 1 Line 3 - compute the gradient of f(P) = -tr(APB^tP^t) + grad_fp = (const_sum + A22 @ P @ B22.T + A22.T @ P @ B22) + # [1] Algorithm 1 Line 4 - get direction Q by solving Eq. 8 + _, cols = linear_sum_assignment(grad_fp, maximize=maximize) + Q = np.eye(n_unseed)[cols] + + # [1] Algorithm 1 Line 5 - compute the step size + # Noting that e.g. trace(Ax) = trace(A)*x, expand and re-collect + # terms as ax**2 + bx + c. c does not affect location of minimum + # and can be ignored. Also, note that trace(A@B) = (A.T*B).sum(); + # apply where possible for efficiency. + R = P - Q + b21 = ((R.T @ A21) * B21).sum() + b12 = ((R.T @ A12.T) * B12.T).sum() + AR22 = A22.T @ R + BR22 = B22 @ R.T + b22a = (AR22 * B22.T[cols]).sum() + b22b = (A22 * BR22[cols]).sum() + a = (AR22.T * BR22).sum() + b = b21 + b12 + b22a + b22b + # critical point of ax^2 + bx + c is at x = -d/(2*e) + # if a * obj_func_scalar > 0, it is a minimum + # if minimum is not in [0, 1], only endpoints need to be considered + if a*obj_func_scalar > 0 and 0 <= -b/(2*a) <= 1: + alpha = -b/(2*a) + else: + alpha = np.argmin([0, (b + a)*obj_func_scalar]) + + # [1] Algorithm 1 Line 6 - Update P + P_i1 = alpha * P + (1 - alpha) * Q + if np.linalg.norm(P - P_i1) / np.sqrt(n_unseed) < tol: + P = P_i1 + break + P = P_i1 + # [1] Algorithm 1 Line 7 - end main loop + + # [1] Algorithm 1 Line 8 - project onto the set of permutation matrices + _, col = linear_sum_assignment(P, maximize=True) + perm = np.concatenate((np.arange(n_seeds), col + n_seeds)) + + unshuffled_perm = np.zeros(n, dtype=int) + unshuffled_perm[perm_A] = perm_B[perm] + + score = _calc_score(A, B, unshuffled_perm) + res = {"col_ind": unshuffled_perm, "fun": score, "nit": n_iter} + return OptimizeResult(res) + + +def _split_matrix(X, n): + # definitions according to Seeded Graph Matching [2]. + upper, lower = X[:n], X[n:] + return upper[:, :n], upper[:, n:], lower[:, :n], lower[:, n:] + + +def _doubly_stochastic(P, tol=1e-3): + # Adapted from @btaba implementation + # https://github.com/btaba/sinkhorn_knopp + # of Sinkhorn-Knopp algorithm + # https://projecteuclid.org/euclid.pjm/1102992505 + + max_iter = 1000 + c = 1 / P.sum(axis=0) + r = 1 / (P @ c) + P_eps = P + + for it in range(max_iter): + if ((np.abs(P_eps.sum(axis=1) - 1) < tol).all() and + (np.abs(P_eps.sum(axis=0) - 1) < tol).all()): + # All column/row sums ~= 1 within threshold + break + + c = 1 / (r @ P) + r = 1 / (P @ c) + P_eps = r[:, None] * P * c + + return P_eps + + +def _quadratic_assignment_2opt(A, B, maximize=False, rng=None, + partial_match=None, + partial_guess=None, + **unknown_options): + r"""Solve the quadratic assignment problem (approximately). + + This function solves the Quadratic Assignment Problem (QAP) and the + Graph Matching Problem (GMP) using the 2-opt algorithm [1]_. + + Quadratic assignment solves problems of the following form: + + .. math:: + + \min_P & \ {\ \text{trace}(A^T P B P^T)}\\ + \mbox{s.t. } & {P \ \epsilon \ \mathcal{P}}\\ + + where :math:`\mathcal{P}` is the set of all permutation matrices, + and :math:`A` and :math:`B` are square matrices. + + Graph matching tries to *maximize* the same objective function. + This algorithm can be thought of as finding the alignment of the + nodes of two graphs that minimizes the number of induced edge + disagreements, or, in the case of weighted graphs, the sum of squared + edge weight differences. + + Note that the quadratic assignment problem is NP-hard. The results given + here are approximations and are not guaranteed to be optimal. + + Parameters + ---------- + A : 2-D array, square + The square matrix :math:`A` in the objective function above. + B : 2-D array, square + The square matrix :math:`B` in the objective function above. + method : str in {'faq', '2opt'} (default: 'faq') + The algorithm used to solve the problem. This is the method-specific + documentation for '2opt'. + :ref:`'faq' ` is also available. + + Options + ------- + maximize : bool (default: False) + Maximizes the objective function if ``True``. + rng : {None, int, `numpy.random.Generator`, + `numpy.random.RandomState`}, optional + + If `seed` is None (or `np.random`), the `numpy.random.RandomState` + singleton is used. + If `seed` is an int, a new ``RandomState`` instance is used, + seeded with `seed`. + If `seed` is already a ``Generator`` or ``RandomState`` instance then + that instance is used. + partial_match : 2-D array of integers, optional (default: None) + Fixes part of the matching. Also known as a "seed" [2]_. + + Each row of `partial_match` specifies a pair of matched nodes: node + ``partial_match[i, 0]`` of `A` is matched to node + ``partial_match[i, 1]`` of `B`. The array has shape ``(m, 2)``, + where ``m`` is not greater than the number of nodes, :math:`n`. + + .. note:: + `partial_match` must be sorted by the first column. + + partial_guess : 2-D array of integers, optional (default: None) + A guess for the matching between the two matrices. Unlike + `partial_match`, `partial_guess` does not fix the indices; they are + still free to be optimized. + + Each row of `partial_guess` specifies a pair of matched nodes: node + ``partial_guess[i, 0]`` of `A` is matched to node + ``partial_guess[i, 1]`` of `B`. The array has shape ``(m, 2)``, + where ``m`` is not greater than the number of nodes, :math:`n`. + + .. note:: + `partial_guess` must be sorted by the first column. + + Returns + ------- + res : OptimizeResult + `OptimizeResult` containing the following fields. + + col_ind : 1-D array + Column indices corresponding to the best permutation found of the + nodes of `B`. + fun : float + The objective value of the solution. + nit : int + The number of iterations performed during optimization. + + Notes + ----- + This is a greedy algorithm that works similarly to bubble sort: beginning + with an initial permutation, it iteratively swaps pairs of indices to + improve the objective function until no such improvements are possible. + + References + ---------- + .. [1] "2-opt," Wikipedia. + https://en.wikipedia.org/wiki/2-opt + + .. [2] D. Fishkind, S. Adali, H. Patsolic, L. Meng, D. Singh, V. Lyzinski, + C. Priebe, "Seeded graph matching", Pattern Recognit. 87 (2019): + 203-215, https://doi.org/10.1016/j.patcog.2018.09.014 + + """ + _check_unknown_options(unknown_options) + rng = check_random_state(rng) + A, B, partial_match = _common_input_validation(A, B, partial_match) + + N = len(A) + # check trivial cases + if N == 0 or partial_match.shape[0] == N: + score = _calc_score(A, B, partial_match[:, 1]) + res = {"col_ind": partial_match[:, 1], "fun": score, "nit": 0} + return OptimizeResult(res) + + if partial_guess is None: + partial_guess = np.array([[], []]).T + partial_guess = np.atleast_2d(partial_guess).astype(int) + + msg = None + if partial_guess.shape[0] > A.shape[0]: + msg = ("`partial_guess` can have only as " + "many entries as there are nodes") + elif partial_guess.shape[1] != 2: + msg = "`partial_guess` must have two columns" + elif partial_guess.ndim != 2: + msg = "`partial_guess` must have exactly two dimensions" + elif (partial_guess < 0).any(): + msg = "`partial_guess` must contain only positive indices" + elif (partial_guess >= len(A)).any(): + msg = "`partial_guess` entries must be less than number of nodes" + elif (not len(set(partial_guess[:, 0])) == len(partial_guess[:, 0]) or + not len(set(partial_guess[:, 1])) == len(partial_guess[:, 1])): + msg = "`partial_guess` column entries must be unique" + if msg is not None: + raise ValueError(msg) + + fixed_rows = None + if partial_match.size or partial_guess.size: + # use partial_match and partial_guess for initial permutation, + # but randomly permute the rest. + guess_rows = np.zeros(N, dtype=bool) + guess_cols = np.zeros(N, dtype=bool) + fixed_rows = np.zeros(N, dtype=bool) + fixed_cols = np.zeros(N, dtype=bool) + perm = np.zeros(N, dtype=int) + + rg, cg = partial_guess.T + guess_rows[rg] = True + guess_cols[cg] = True + perm[guess_rows] = cg + + # match overrides guess + rf, cf = partial_match.T + fixed_rows[rf] = True + fixed_cols[cf] = True + perm[fixed_rows] = cf + + random_rows = ~fixed_rows & ~guess_rows + random_cols = ~fixed_cols & ~guess_cols + perm[random_rows] = rng.permutation(np.arange(N)[random_cols]) + else: + perm = rng.permutation(np.arange(N)) + + best_score = _calc_score(A, B, perm) + + i_free = np.arange(N) + if fixed_rows is not None: + i_free = i_free[~fixed_rows] + + better = operator.gt if maximize else operator.lt + n_iter = 0 + done = False + while not done: + # equivalent to nested for loops i in range(N), j in range(i, N) + for i, j in itertools.combinations_with_replacement(i_free, 2): + n_iter += 1 + perm[i], perm[j] = perm[j], perm[i] + score = _calc_score(A, B, perm) + if better(score, best_score): + best_score = score + break + # faster to swap back than to create a new list every time + perm[i], perm[j] = perm[j], perm[i] + else: # no swaps made + done = True + + res = {"col_ind": perm, "fun": best_score, "nit": n_iter} + return OptimizeResult(res) diff --git a/llava_next/lib/python3.10/site-packages/scipy/optimize/_remove_redundancy.py b/llava_next/lib/python3.10/site-packages/scipy/optimize/_remove_redundancy.py new file mode 100644 index 0000000000000000000000000000000000000000..cb81ad1696b768d2304b2fc42a80cc9678cbde00 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/scipy/optimize/_remove_redundancy.py @@ -0,0 +1,522 @@ +""" +Routines for removing redundant (linearly dependent) equations from linear +programming equality constraints. +""" +# Author: Matt Haberland + +import numpy as np +from scipy.linalg import svd +from scipy.linalg.interpolative import interp_decomp +import scipy +from scipy.linalg.blas import dtrsm + + +def _row_count(A): + """ + Counts the number of nonzeros in each row of input array A. + Nonzeros are defined as any element with absolute value greater than + tol = 1e-13. This value should probably be an input to the function. + + Parameters + ---------- + A : 2-D array + An array representing a matrix + + Returns + ------- + rowcount : 1-D array + Number of nonzeros in each row of A + + """ + tol = 1e-13 + return np.array((abs(A) > tol).sum(axis=1)).flatten() + + +def _get_densest(A, eligibleRows): + """ + Returns the index of the densest row of A. Ignores rows that are not + eligible for consideration. + + Parameters + ---------- + A : 2-D array + An array representing a matrix + eligibleRows : 1-D logical array + Values indicate whether the corresponding row of A is eligible + to be considered + + Returns + ------- + i_densest : int + Index of the densest row in A eligible for consideration + + """ + rowCounts = _row_count(A) + return np.argmax(rowCounts * eligibleRows) + + +def _remove_zero_rows(A, b): + """ + Eliminates trivial equations from system of equations defined by Ax = b + and identifies trivial infeasibilities + + Parameters + ---------- + A : 2-D array + An array representing the left-hand side of a system of equations + b : 1-D array + An array representing the right-hand side of a system of equations + + Returns + ------- + A : 2-D array + An array representing the left-hand side of a system of equations + b : 1-D array + An array representing the right-hand side of a system of equations + status: int + An integer indicating the status of the removal operation + 0: No infeasibility identified + 2: Trivially infeasible + message : str + A string descriptor of the exit status of the optimization. + + """ + status = 0 + message = "" + i_zero = _row_count(A) == 0 + A = A[np.logical_not(i_zero), :] + if not np.allclose(b[i_zero], 0): + status = 2 + message = "There is a zero row in A_eq with a nonzero corresponding " \ + "entry in b_eq. The problem is infeasible." + b = b[np.logical_not(i_zero)] + return A, b, status, message + + +def bg_update_dense(plu, perm_r, v, j): + LU, p = plu + + vperm = v[perm_r] + u = dtrsm(1, LU, vperm, lower=1, diag=1) + LU[:j+1, j] = u[:j+1] + l = u[j+1:] + piv = LU[j, j] + LU[j+1:, j] += (l/piv) + return LU, p + + +def _remove_redundancy_pivot_dense(A, rhs, true_rank=None): + """ + Eliminates redundant equations from system of equations defined by Ax = b + and identifies infeasibilities. + + Parameters + ---------- + A : 2-D sparse matrix + An matrix representing the left-hand side of a system of equations + rhs : 1-D array + An array representing the right-hand side of a system of equations + + Returns + ------- + A : 2-D sparse matrix + A matrix representing the left-hand side of a system of equations + rhs : 1-D array + An array representing the right-hand side of a system of equations + status: int + An integer indicating the status of the system + 0: No infeasibility identified + 2: Trivially infeasible + message : str + A string descriptor of the exit status of the optimization. + + References + ---------- + .. [2] Andersen, Erling D. "Finding all linearly dependent rows in + large-scale linear programming." Optimization Methods and Software + 6.3 (1995): 219-227. + + """ + tolapiv = 1e-8 + tolprimal = 1e-8 + status = 0 + message = "" + inconsistent = ("There is a linear combination of rows of A_eq that " + "results in zero, suggesting a redundant constraint. " + "However the same linear combination of b_eq is " + "nonzero, suggesting that the constraints conflict " + "and the problem is infeasible.") + A, rhs, status, message = _remove_zero_rows(A, rhs) + + if status != 0: + return A, rhs, status, message + + m, n = A.shape + + v = list(range(m)) # Artificial column indices. + b = list(v) # Basis column indices. + # This is better as a list than a set because column order of basis matrix + # needs to be consistent. + d = [] # Indices of dependent rows + perm_r = None + + A_orig = A + A = np.zeros((m, m + n), order='F') + np.fill_diagonal(A, 1) + A[:, m:] = A_orig + e = np.zeros(m) + + js_candidates = np.arange(m, m+n, dtype=int) # candidate columns for basis + # manual masking was faster than masked array + js_mask = np.ones(js_candidates.shape, dtype=bool) + + # Implements basic algorithm from [2] + # Uses some of the suggested improvements (removing zero rows and + # Bartels-Golub update idea). + # Removing column singletons would be easy, but it is not as important + # because the procedure is performed only on the equality constraint + # matrix from the original problem - not on the canonical form matrix, + # which would have many more column singletons due to slack variables + # from the inequality constraints. + # The thoughts on "crashing" the initial basis are only really useful if + # the matrix is sparse. + + lu = np.eye(m, order='F'), np.arange(m) # initial LU is trivial + perm_r = lu[1] + for i in v: + + e[i] = 1 + if i > 0: + e[i-1] = 0 + + try: # fails for i==0 and any time it gets ill-conditioned + j = b[i-1] + lu = bg_update_dense(lu, perm_r, A[:, j], i-1) + except Exception: + lu = scipy.linalg.lu_factor(A[:, b]) + LU, p = lu + perm_r = list(range(m)) + for i1, i2 in enumerate(p): + perm_r[i1], perm_r[i2] = perm_r[i2], perm_r[i1] + + pi = scipy.linalg.lu_solve(lu, e, trans=1) + + js = js_candidates[js_mask] + batch = 50 + + # This is a tiny bit faster than looping over columns individually, + # like for j in js: if abs(A[:,j].transpose().dot(pi)) > tolapiv: + for j_index in range(0, len(js), batch): + j_indices = js[j_index: min(j_index+batch, len(js))] + + c = abs(A[:, j_indices].transpose().dot(pi)) + if (c > tolapiv).any(): + j = js[j_index + np.argmax(c)] # very independent column + b[i] = j + js_mask[j-m] = False + break + else: + bibar = pi.T.dot(rhs.reshape(-1, 1)) + bnorm = np.linalg.norm(rhs) + if abs(bibar)/(1+bnorm) > tolprimal: # inconsistent + status = 2 + message = inconsistent + return A_orig, rhs, status, message + else: # dependent + d.append(i) + if true_rank is not None and len(d) == m - true_rank: + break # found all redundancies + + keep = set(range(m)) + keep = list(keep - set(d)) + return A_orig[keep, :], rhs[keep], status, message + + +def _remove_redundancy_pivot_sparse(A, rhs): + """ + Eliminates redundant equations from system of equations defined by Ax = b + and identifies infeasibilities. + + Parameters + ---------- + A : 2-D sparse matrix + An matrix representing the left-hand side of a system of equations + rhs : 1-D array + An array representing the right-hand side of a system of equations + + Returns + ------- + A : 2-D sparse matrix + A matrix representing the left-hand side of a system of equations + rhs : 1-D array + An array representing the right-hand side of a system of equations + status: int + An integer indicating the status of the system + 0: No infeasibility identified + 2: Trivially infeasible + message : str + A string descriptor of the exit status of the optimization. + + References + ---------- + .. [2] Andersen, Erling D. "Finding all linearly dependent rows in + large-scale linear programming." Optimization Methods and Software + 6.3 (1995): 219-227. + + """ + + tolapiv = 1e-8 + tolprimal = 1e-8 + status = 0 + message = "" + inconsistent = ("There is a linear combination of rows of A_eq that " + "results in zero, suggesting a redundant constraint. " + "However the same linear combination of b_eq is " + "nonzero, suggesting that the constraints conflict " + "and the problem is infeasible.") + A, rhs, status, message = _remove_zero_rows(A, rhs) + + if status != 0: + return A, rhs, status, message + + m, n = A.shape + + v = list(range(m)) # Artificial column indices. + b = list(v) # Basis column indices. + # This is better as a list than a set because column order of basis matrix + # needs to be consistent. + k = set(range(m, m+n)) # Structural column indices. + d = [] # Indices of dependent rows + + A_orig = A + A = scipy.sparse.hstack((scipy.sparse.eye(m), A)).tocsc() + e = np.zeros(m) + + # Implements basic algorithm from [2] + # Uses only one of the suggested improvements (removing zero rows). + # Removing column singletons would be easy, but it is not as important + # because the procedure is performed only on the equality constraint + # matrix from the original problem - not on the canonical form matrix, + # which would have many more column singletons due to slack variables + # from the inequality constraints. + # The thoughts on "crashing" the initial basis sound useful, but the + # description of the procedure seems to assume a lot of familiarity with + # the subject; it is not very explicit. I already went through enough + # trouble getting the basic algorithm working, so I was not interested in + # trying to decipher this, too. (Overall, the paper is fraught with + # mistakes and ambiguities - which is strange, because the rest of + # Andersen's papers are quite good.) + # I tried and tried and tried to improve performance using the + # Bartels-Golub update. It works, but it's only practical if the LU + # factorization can be specialized as described, and that is not possible + # until the SciPy SuperLU interface permits control over column + # permutation - see issue #7700. + + for i in v: + B = A[:, b] + + e[i] = 1 + if i > 0: + e[i-1] = 0 + + pi = scipy.sparse.linalg.spsolve(B.transpose(), e).reshape(-1, 1) + + js = list(k-set(b)) # not efficient, but this is not the time sink... + + # Due to overhead, it tends to be faster (for problems tested) to + # compute the full matrix-vector product rather than individual + # vector-vector products (with the chance of terminating as soon + # as any are nonzero). For very large matrices, it might be worth + # it to compute, say, 100 or 1000 at a time and stop when a nonzero + # is found. + + c = (np.abs(A[:, js].transpose().dot(pi)) > tolapiv).nonzero()[0] + if len(c) > 0: # independent + j = js[c[0]] + # in a previous commit, the previous line was changed to choose + # index j corresponding with the maximum dot product. + # While this avoided issues with almost + # singular matrices, it slowed the routine in most NETLIB tests. + # I think this is because these columns were denser than the + # first column with nonzero dot product (c[0]). + # It would be nice to have a heuristic that balances sparsity with + # high dot product, but I don't think it's worth the time to + # develop one right now. Bartels-Golub update is a much higher + # priority. + b[i] = j # replace artificial column + else: + bibar = pi.T.dot(rhs.reshape(-1, 1)) + bnorm = np.linalg.norm(rhs) + if abs(bibar)/(1 + bnorm) > tolprimal: + status = 2 + message = inconsistent + return A_orig, rhs, status, message + else: # dependent + d.append(i) + + keep = set(range(m)) + keep = list(keep - set(d)) + return A_orig[keep, :], rhs[keep], status, message + + +def _remove_redundancy_svd(A, b): + """ + Eliminates redundant equations from system of equations defined by Ax = b + and identifies infeasibilities. + + Parameters + ---------- + A : 2-D array + An array representing the left-hand side of a system of equations + b : 1-D array + An array representing the right-hand side of a system of equations + + Returns + ------- + A : 2-D array + An array representing the left-hand side of a system of equations + b : 1-D array + An array representing the right-hand side of a system of equations + status: int + An integer indicating the status of the system + 0: No infeasibility identified + 2: Trivially infeasible + message : str + A string descriptor of the exit status of the optimization. + + References + ---------- + .. [2] Andersen, Erling D. "Finding all linearly dependent rows in + large-scale linear programming." Optimization Methods and Software + 6.3 (1995): 219-227. + + """ + + A, b, status, message = _remove_zero_rows(A, b) + + if status != 0: + return A, b, status, message + + U, s, Vh = svd(A) + eps = np.finfo(float).eps + tol = s.max() * max(A.shape) * eps + + m, n = A.shape + s_min = s[-1] if m <= n else 0 + + # this algorithm is faster than that of [2] when the nullspace is small + # but it could probably be improvement by randomized algorithms and with + # a sparse implementation. + # it relies on repeated singular value decomposition to find linearly + # dependent rows (as identified by columns of U that correspond with zero + # singular values). Unfortunately, only one row can be removed per + # decomposition (I tried otherwise; doing so can cause problems.) + # It would be nice if we could do truncated SVD like sp.sparse.linalg.svds + # but that function is unreliable at finding singular values near zero. + # Finding max eigenvalue L of A A^T, then largest eigenvalue (and + # associated eigenvector) of -A A^T + L I (I is identity) via power + # iteration would also work in theory, but is only efficient if the + # smallest nonzero eigenvalue of A A^T is close to the largest nonzero + # eigenvalue. + + while abs(s_min) < tol: + v = U[:, -1] # TODO: return these so user can eliminate from problem? + # rows need to be represented in significant amount + eligibleRows = np.abs(v) > tol * 10e6 + if not np.any(eligibleRows) or np.any(np.abs(v.dot(A)) > tol): + status = 4 + message = ("Due to numerical issues, redundant equality " + "constraints could not be removed automatically. " + "Try providing your constraint matrices as sparse " + "matrices to activate sparse presolve, try turning " + "off redundancy removal, or try turning off presolve " + "altogether.") + break + if np.any(np.abs(v.dot(b)) > tol * 100): # factor of 100 to fix 10038 and 10349 + status = 2 + message = ("There is a linear combination of rows of A_eq that " + "results in zero, suggesting a redundant constraint. " + "However the same linear combination of b_eq is " + "nonzero, suggesting that the constraints conflict " + "and the problem is infeasible.") + break + + i_remove = _get_densest(A, eligibleRows) + A = np.delete(A, i_remove, axis=0) + b = np.delete(b, i_remove) + U, s, Vh = svd(A) + m, n = A.shape + s_min = s[-1] if m <= n else 0 + + return A, b, status, message + + +def _remove_redundancy_id(A, rhs, rank=None, randomized=True): + """Eliminates redundant equations from a system of equations. + + Eliminates redundant equations from system of equations defined by Ax = b + and identifies infeasibilities. + + Parameters + ---------- + A : 2-D array + An array representing the left-hand side of a system of equations + rhs : 1-D array + An array representing the right-hand side of a system of equations + rank : int, optional + The rank of A + randomized: bool, optional + True for randomized interpolative decomposition + + Returns + ------- + A : 2-D array + An array representing the left-hand side of a system of equations + rhs : 1-D array + An array representing the right-hand side of a system of equations + status: int + An integer indicating the status of the system + 0: No infeasibility identified + 2: Trivially infeasible + message : str + A string descriptor of the exit status of the optimization. + + """ + + status = 0 + message = "" + inconsistent = ("There is a linear combination of rows of A_eq that " + "results in zero, suggesting a redundant constraint. " + "However the same linear combination of b_eq is " + "nonzero, suggesting that the constraints conflict " + "and the problem is infeasible.") + + A, rhs, status, message = _remove_zero_rows(A, rhs) + + if status != 0: + return A, rhs, status, message + + m, n = A.shape + + k = rank + if rank is None: + k = np.linalg.matrix_rank(A) + + idx, proj = interp_decomp(A.T, k, rand=randomized) + + # first k entries in idx are indices of the independent rows + # remaining entries are the indices of the m-k dependent rows + # proj provides a linear combinations of rows of A2 that form the + # remaining m-k (dependent) rows. The same linear combination of entries + # in rhs2 must give the remaining m-k entries. If not, the system is + # inconsistent, and the problem is infeasible. + if not np.allclose(rhs[idx[:k]] @ proj, rhs[idx[k:]]): + status = 2 + message = inconsistent + + # sort indices because the other redundancy removal routines leave rows + # in original order and tests were written with that in mind + idx = sorted(idx[:k]) + A2 = A[idx, :] + rhs2 = rhs[idx] + return A2, rhs2, status, message diff --git a/llava_next/lib/python3.10/site-packages/scipy/optimize/_root.py b/llava_next/lib/python3.10/site-packages/scipy/optimize/_root.py new file mode 100644 index 0000000000000000000000000000000000000000..2847619bb8039af0c3f96ce5b3347a082ad449e2 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/scipy/optimize/_root.py @@ -0,0 +1,732 @@ +""" +Unified interfaces to root finding algorithms. + +Functions +--------- +- root : find a root of a vector function. +""" +__all__ = ['root'] + +import numpy as np + +from warnings import warn + +from ._optimize import MemoizeJac, OptimizeResult, _check_unknown_options +from ._minpack_py import _root_hybr, leastsq +from ._spectral import _root_df_sane +from . import _nonlin as nonlin + + +ROOT_METHODS = ['hybr', 'lm', 'broyden1', 'broyden2', 'anderson', + 'linearmixing', 'diagbroyden', 'excitingmixing', 'krylov', + 'df-sane'] + + +def root(fun, x0, args=(), method='hybr', jac=None, tol=None, callback=None, + options=None): + r""" + Find a root of a vector function. + + Parameters + ---------- + fun : callable + A vector function to find a root of. + x0 : ndarray + Initial guess. + args : tuple, optional + Extra arguments passed to the objective function and its Jacobian. + method : str, optional + Type of solver. Should be one of + + - 'hybr' :ref:`(see here) ` + - 'lm' :ref:`(see here) ` + - 'broyden1' :ref:`(see here) ` + - 'broyden2' :ref:`(see here) ` + - 'anderson' :ref:`(see here) ` + - 'linearmixing' :ref:`(see here) ` + - 'diagbroyden' :ref:`(see here) ` + - 'excitingmixing' :ref:`(see here) ` + - 'krylov' :ref:`(see here) ` + - 'df-sane' :ref:`(see here) ` + + jac : bool or callable, optional + If `jac` is a Boolean and is True, `fun` is assumed to return the + value of Jacobian along with the objective function. If False, the + Jacobian will be estimated numerically. + `jac` can also be a callable returning the Jacobian of `fun`. In + this case, it must accept the same arguments as `fun`. + tol : float, optional + Tolerance for termination. For detailed control, use solver-specific + options. + callback : function, optional + Optional callback function. It is called on every iteration as + ``callback(x, f)`` where `x` is the current solution and `f` + the corresponding residual. For all methods but 'hybr' and 'lm'. + options : dict, optional + A dictionary of solver options. E.g., `xtol` or `maxiter`, see + :obj:`show_options()` for details. + + Returns + ------- + sol : OptimizeResult + The solution represented as a ``OptimizeResult`` object. + Important attributes are: ``x`` the solution array, ``success`` a + Boolean flag indicating if the algorithm exited successfully and + ``message`` which describes the cause of the termination. See + `OptimizeResult` for a description of other attributes. + + See also + -------- + show_options : Additional options accepted by the solvers + + Notes + ----- + This section describes the available solvers that can be selected by the + 'method' parameter. The default method is *hybr*. + + Method *hybr* uses a modification of the Powell hybrid method as + implemented in MINPACK [1]_. + + Method *lm* solves the system of nonlinear equations in a least squares + sense using a modification of the Levenberg-Marquardt algorithm as + implemented in MINPACK [1]_. + + Method *df-sane* is a derivative-free spectral method. [3]_ + + Methods *broyden1*, *broyden2*, *anderson*, *linearmixing*, + *diagbroyden*, *excitingmixing*, *krylov* are inexact Newton methods, + with backtracking or full line searches [2]_. Each method corresponds + to a particular Jacobian approximations. + + - Method *broyden1* uses Broyden's first Jacobian approximation, it is + known as Broyden's good method. + - Method *broyden2* uses Broyden's second Jacobian approximation, it + is known as Broyden's bad method. + - Method *anderson* uses (extended) Anderson mixing. + - Method *Krylov* uses Krylov approximation for inverse Jacobian. It + is suitable for large-scale problem. + - Method *diagbroyden* uses diagonal Broyden Jacobian approximation. + - Method *linearmixing* uses a scalar Jacobian approximation. + - Method *excitingmixing* uses a tuned diagonal Jacobian + approximation. + + .. warning:: + + The algorithms implemented for methods *diagbroyden*, + *linearmixing* and *excitingmixing* may be useful for specific + problems, but whether they will work may depend strongly on the + problem. + + .. versionadded:: 0.11.0 + + References + ---------- + .. [1] More, Jorge J., Burton S. Garbow, and Kenneth E. Hillstrom. + 1980. User Guide for MINPACK-1. + .. [2] C. T. Kelley. 1995. Iterative Methods for Linear and Nonlinear + Equations. Society for Industrial and Applied Mathematics. + + .. [3] W. La Cruz, J.M. Martinez, M. Raydan. Math. Comp. 75, 1429 (2006). + + Examples + -------- + The following functions define a system of nonlinear equations and its + jacobian. + + >>> import numpy as np + >>> def fun(x): + ... return [x[0] + 0.5 * (x[0] - x[1])**3 - 1.0, + ... 0.5 * (x[1] - x[0])**3 + x[1]] + + >>> def jac(x): + ... return np.array([[1 + 1.5 * (x[0] - x[1])**2, + ... -1.5 * (x[0] - x[1])**2], + ... [-1.5 * (x[1] - x[0])**2, + ... 1 + 1.5 * (x[1] - x[0])**2]]) + + A solution can be obtained as follows. + + >>> from scipy import optimize + >>> sol = optimize.root(fun, [0, 0], jac=jac, method='hybr') + >>> sol.x + array([ 0.8411639, 0.1588361]) + + **Large problem** + + Suppose that we needed to solve the following integrodifferential + equation on the square :math:`[0,1]\times[0,1]`: + + .. math:: + + \nabla^2 P = 10 \left(\int_0^1\int_0^1\cosh(P)\,dx\,dy\right)^2 + + with :math:`P(x,1) = 1` and :math:`P=0` elsewhere on the boundary of + the square. + + The solution can be found using the ``method='krylov'`` solver: + + >>> from scipy import optimize + >>> # parameters + >>> nx, ny = 75, 75 + >>> hx, hy = 1./(nx-1), 1./(ny-1) + + >>> P_left, P_right = 0, 0 + >>> P_top, P_bottom = 1, 0 + + >>> def residual(P): + ... d2x = np.zeros_like(P) + ... d2y = np.zeros_like(P) + ... + ... d2x[1:-1] = (P[2:] - 2*P[1:-1] + P[:-2]) / hx/hx + ... d2x[0] = (P[1] - 2*P[0] + P_left)/hx/hx + ... d2x[-1] = (P_right - 2*P[-1] + P[-2])/hx/hx + ... + ... d2y[:,1:-1] = (P[:,2:] - 2*P[:,1:-1] + P[:,:-2])/hy/hy + ... d2y[:,0] = (P[:,1] - 2*P[:,0] + P_bottom)/hy/hy + ... d2y[:,-1] = (P_top - 2*P[:,-1] + P[:,-2])/hy/hy + ... + ... return d2x + d2y - 10*np.cosh(P).mean()**2 + + >>> guess = np.zeros((nx, ny), float) + >>> sol = optimize.root(residual, guess, method='krylov') + >>> print('Residual: %g' % abs(residual(sol.x)).max()) + Residual: 5.7972e-06 # may vary + + >>> import matplotlib.pyplot as plt + >>> x, y = np.mgrid[0:1:(nx*1j), 0:1:(ny*1j)] + >>> plt.pcolormesh(x, y, sol.x, shading='gouraud') + >>> plt.colorbar() + >>> plt.show() + + """ + def _wrapped_fun(*fargs): + """ + Wrapped `func` to track the number of times + the function has been called. + """ + _wrapped_fun.nfev += 1 + return fun(*fargs) + + _wrapped_fun.nfev = 0 + + if not isinstance(args, tuple): + args = (args,) + + meth = method.lower() + if options is None: + options = {} + + if callback is not None and meth in ('hybr', 'lm'): + warn('Method %s does not accept callback.' % method, + RuntimeWarning, stacklevel=2) + + # fun also returns the Jacobian + if not callable(jac) and meth in ('hybr', 'lm'): + if bool(jac): + fun = MemoizeJac(fun) + jac = fun.derivative + else: + jac = None + + # set default tolerances + if tol is not None: + options = dict(options) + if meth in ('hybr', 'lm'): + options.setdefault('xtol', tol) + elif meth in ('df-sane',): + options.setdefault('ftol', tol) + elif meth in ('broyden1', 'broyden2', 'anderson', 'linearmixing', + 'diagbroyden', 'excitingmixing', 'krylov'): + options.setdefault('xtol', tol) + options.setdefault('xatol', np.inf) + options.setdefault('ftol', np.inf) + options.setdefault('fatol', np.inf) + + if meth == 'hybr': + sol = _root_hybr(_wrapped_fun, x0, args=args, jac=jac, **options) + elif meth == 'lm': + sol = _root_leastsq(_wrapped_fun, x0, args=args, jac=jac, **options) + elif meth == 'df-sane': + _warn_jac_unused(jac, method) + sol = _root_df_sane(_wrapped_fun, x0, args=args, callback=callback, + **options) + elif meth in ('broyden1', 'broyden2', 'anderson', 'linearmixing', + 'diagbroyden', 'excitingmixing', 'krylov'): + _warn_jac_unused(jac, method) + sol = _root_nonlin_solve(_wrapped_fun, x0, args=args, jac=jac, + _method=meth, _callback=callback, + **options) + else: + raise ValueError('Unknown solver %s' % method) + + sol.nfev = _wrapped_fun.nfev + return sol + + +def _warn_jac_unused(jac, method): + if jac is not None: + warn(f'Method {method} does not use the jacobian (jac).', + RuntimeWarning, stacklevel=2) + + +def _root_leastsq(fun, x0, args=(), jac=None, + col_deriv=0, xtol=1.49012e-08, ftol=1.49012e-08, + gtol=0.0, maxiter=0, eps=0.0, factor=100, diag=None, + **unknown_options): + """ + Solve for least squares with Levenberg-Marquardt + + Options + ------- + col_deriv : bool + non-zero to specify that the Jacobian function computes derivatives + down the columns (faster, because there is no transpose operation). + ftol : float + Relative error desired in the sum of squares. + xtol : float + Relative error desired in the approximate solution. + gtol : float + Orthogonality desired between the function vector and the columns + of the Jacobian. + maxiter : int + The maximum number of calls to the function. If zero, then + 100*(N+1) is the maximum where N is the number of elements in x0. + eps : float + A suitable step length for the forward-difference approximation of + the Jacobian (for Dfun=None). If `eps` is less than the machine + precision, it is assumed that the relative errors in the functions + are of the order of the machine precision. + factor : float + A parameter determining the initial step bound + (``factor * || diag * x||``). Should be in interval ``(0.1, 100)``. + diag : sequence + N positive entries that serve as a scale factors for the variables. + """ + nfev = 0 + def _wrapped_fun(*fargs): + """ + Wrapped `func` to track the number of times + the function has been called. + """ + nonlocal nfev + nfev += 1 + return fun(*fargs) + + _check_unknown_options(unknown_options) + x, cov_x, info, msg, ier = leastsq(_wrapped_fun, x0, args=args, + Dfun=jac, full_output=True, + col_deriv=col_deriv, xtol=xtol, + ftol=ftol, gtol=gtol, + maxfev=maxiter, epsfcn=eps, + factor=factor, diag=diag) + sol = OptimizeResult(x=x, message=msg, status=ier, + success=ier in (1, 2, 3, 4), cov_x=cov_x, + fun=info.pop('fvec'), method="lm") + sol.update(info) + sol.nfev = nfev + return sol + + +def _root_nonlin_solve(fun, x0, args=(), jac=None, + _callback=None, _method=None, + nit=None, disp=False, maxiter=None, + ftol=None, fatol=None, xtol=None, xatol=None, + tol_norm=None, line_search='armijo', jac_options=None, + **unknown_options): + _check_unknown_options(unknown_options) + + f_tol = fatol + f_rtol = ftol + x_tol = xatol + x_rtol = xtol + verbose = disp + if jac_options is None: + jac_options = dict() + + jacobian = {'broyden1': nonlin.BroydenFirst, + 'broyden2': nonlin.BroydenSecond, + 'anderson': nonlin.Anderson, + 'linearmixing': nonlin.LinearMixing, + 'diagbroyden': nonlin.DiagBroyden, + 'excitingmixing': nonlin.ExcitingMixing, + 'krylov': nonlin.KrylovJacobian + }[_method] + + if args: + if jac is True: + def f(x): + return fun(x, *args)[0] + else: + def f(x): + return fun(x, *args) + else: + f = fun + + x, info = nonlin.nonlin_solve(f, x0, jacobian=jacobian(**jac_options), + iter=nit, verbose=verbose, + maxiter=maxiter, f_tol=f_tol, + f_rtol=f_rtol, x_tol=x_tol, + x_rtol=x_rtol, tol_norm=tol_norm, + line_search=line_search, + callback=_callback, full_output=True, + raise_exception=False) + sol = OptimizeResult(x=x, method=_method) + sol.update(info) + return sol + +def _root_broyden1_doc(): + """ + Options + ------- + nit : int, optional + Number of iterations to make. If omitted (default), make as many + as required to meet tolerances. + disp : bool, optional + Print status to stdout on every iteration. + maxiter : int, optional + Maximum number of iterations to make. + ftol : float, optional + Relative tolerance for the residual. If omitted, not used. + fatol : float, optional + Absolute tolerance (in max-norm) for the residual. + If omitted, default is 6e-6. + xtol : float, optional + Relative minimum step size. If omitted, not used. + xatol : float, optional + Absolute minimum step size, as determined from the Jacobian + approximation. If the step size is smaller than this, optimization + is terminated as successful. If omitted, not used. + tol_norm : function(vector) -> scalar, optional + Norm to use in convergence check. Default is the maximum norm. + line_search : {None, 'armijo' (default), 'wolfe'}, optional + Which type of a line search to use to determine the step size in + the direction given by the Jacobian approximation. Defaults to + 'armijo'. + jac_options : dict, optional + Options for the respective Jacobian approximation. + alpha : float, optional + Initial guess for the Jacobian is (-1/alpha). + reduction_method : str or tuple, optional + Method used in ensuring that the rank of the Broyden + matrix stays low. Can either be a string giving the + name of the method, or a tuple of the form ``(method, + param1, param2, ...)`` that gives the name of the + method and values for additional parameters. + + Methods available: + + - ``restart`` + Drop all matrix columns. Has no + extra parameters. + - ``simple`` + Drop oldest matrix column. Has no + extra parameters. + - ``svd`` + Keep only the most significant SVD + components. + + Extra parameters: + + - ``to_retain`` + Number of SVD components to + retain when rank reduction is done. + Default is ``max_rank - 2``. + max_rank : int, optional + Maximum rank for the Broyden matrix. + Default is infinity (i.e., no rank reduction). + + Examples + -------- + >>> def func(x): + ... return np.cos(x) + x[::-1] - [1, 2, 3, 4] + ... + >>> from scipy import optimize + >>> res = optimize.root(func, [1, 1, 1, 1], method='broyden1', tol=1e-14) + >>> x = res.x + >>> x + array([4.04674914, 3.91158389, 2.71791677, 1.61756251]) + >>> np.cos(x) + x[::-1] + array([1., 2., 3., 4.]) + + """ + pass + +def _root_broyden2_doc(): + """ + Options + ------- + nit : int, optional + Number of iterations to make. If omitted (default), make as many + as required to meet tolerances. + disp : bool, optional + Print status to stdout on every iteration. + maxiter : int, optional + Maximum number of iterations to make. + ftol : float, optional + Relative tolerance for the residual. If omitted, not used. + fatol : float, optional + Absolute tolerance (in max-norm) for the residual. + If omitted, default is 6e-6. + xtol : float, optional + Relative minimum step size. If omitted, not used. + xatol : float, optional + Absolute minimum step size, as determined from the Jacobian + approximation. If the step size is smaller than this, optimization + is terminated as successful. If omitted, not used. + tol_norm : function(vector) -> scalar, optional + Norm to use in convergence check. Default is the maximum norm. + line_search : {None, 'armijo' (default), 'wolfe'}, optional + Which type of a line search to use to determine the step size in + the direction given by the Jacobian approximation. Defaults to + 'armijo'. + jac_options : dict, optional + Options for the respective Jacobian approximation. + + alpha : float, optional + Initial guess for the Jacobian is (-1/alpha). + reduction_method : str or tuple, optional + Method used in ensuring that the rank of the Broyden + matrix stays low. Can either be a string giving the + name of the method, or a tuple of the form ``(method, + param1, param2, ...)`` that gives the name of the + method and values for additional parameters. + + Methods available: + + - ``restart`` + Drop all matrix columns. Has no + extra parameters. + - ``simple`` + Drop oldest matrix column. Has no + extra parameters. + - ``svd`` + Keep only the most significant SVD + components. + + Extra parameters: + + - ``to_retain`` + Number of SVD components to + retain when rank reduction is done. + Default is ``max_rank - 2``. + max_rank : int, optional + Maximum rank for the Broyden matrix. + Default is infinity (i.e., no rank reduction). + """ + pass + +def _root_anderson_doc(): + """ + Options + ------- + nit : int, optional + Number of iterations to make. If omitted (default), make as many + as required to meet tolerances. + disp : bool, optional + Print status to stdout on every iteration. + maxiter : int, optional + Maximum number of iterations to make. + ftol : float, optional + Relative tolerance for the residual. If omitted, not used. + fatol : float, optional + Absolute tolerance (in max-norm) for the residual. + If omitted, default is 6e-6. + xtol : float, optional + Relative minimum step size. If omitted, not used. + xatol : float, optional + Absolute minimum step size, as determined from the Jacobian + approximation. If the step size is smaller than this, optimization + is terminated as successful. If omitted, not used. + tol_norm : function(vector) -> scalar, optional + Norm to use in convergence check. Default is the maximum norm. + line_search : {None, 'armijo' (default), 'wolfe'}, optional + Which type of a line search to use to determine the step size in + the direction given by the Jacobian approximation. Defaults to + 'armijo'. + jac_options : dict, optional + Options for the respective Jacobian approximation. + + alpha : float, optional + Initial guess for the Jacobian is (-1/alpha). + M : float, optional + Number of previous vectors to retain. Defaults to 5. + w0 : float, optional + Regularization parameter for numerical stability. + Compared to unity, good values of the order of 0.01. + """ + pass + +def _root_linearmixing_doc(): + """ + Options + ------- + nit : int, optional + Number of iterations to make. If omitted (default), make as many + as required to meet tolerances. + disp : bool, optional + Print status to stdout on every iteration. + maxiter : int, optional + Maximum number of iterations to make. + ftol : float, optional + Relative tolerance for the residual. If omitted, not used. + fatol : float, optional + Absolute tolerance (in max-norm) for the residual. + If omitted, default is 6e-6. + xtol : float, optional + Relative minimum step size. If omitted, not used. + xatol : float, optional + Absolute minimum step size, as determined from the Jacobian + approximation. If the step size is smaller than this, optimization + is terminated as successful. If omitted, not used. + tol_norm : function(vector) -> scalar, optional + Norm to use in convergence check. Default is the maximum norm. + line_search : {None, 'armijo' (default), 'wolfe'}, optional + Which type of a line search to use to determine the step size in + the direction given by the Jacobian approximation. Defaults to + 'armijo'. + jac_options : dict, optional + Options for the respective Jacobian approximation. + + alpha : float, optional + initial guess for the jacobian is (-1/alpha). + """ + pass + +def _root_diagbroyden_doc(): + """ + Options + ------- + nit : int, optional + Number of iterations to make. If omitted (default), make as many + as required to meet tolerances. + disp : bool, optional + Print status to stdout on every iteration. + maxiter : int, optional + Maximum number of iterations to make. + ftol : float, optional + Relative tolerance for the residual. If omitted, not used. + fatol : float, optional + Absolute tolerance (in max-norm) for the residual. + If omitted, default is 6e-6. + xtol : float, optional + Relative minimum step size. If omitted, not used. + xatol : float, optional + Absolute minimum step size, as determined from the Jacobian + approximation. If the step size is smaller than this, optimization + is terminated as successful. If omitted, not used. + tol_norm : function(vector) -> scalar, optional + Norm to use in convergence check. Default is the maximum norm. + line_search : {None, 'armijo' (default), 'wolfe'}, optional + Which type of a line search to use to determine the step size in + the direction given by the Jacobian approximation. Defaults to + 'armijo'. + jac_options : dict, optional + Options for the respective Jacobian approximation. + + alpha : float, optional + initial guess for the jacobian is (-1/alpha). + """ + pass + +def _root_excitingmixing_doc(): + """ + Options + ------- + nit : int, optional + Number of iterations to make. If omitted (default), make as many + as required to meet tolerances. + disp : bool, optional + Print status to stdout on every iteration. + maxiter : int, optional + Maximum number of iterations to make. + ftol : float, optional + Relative tolerance for the residual. If omitted, not used. + fatol : float, optional + Absolute tolerance (in max-norm) for the residual. + If omitted, default is 6e-6. + xtol : float, optional + Relative minimum step size. If omitted, not used. + xatol : float, optional + Absolute minimum step size, as determined from the Jacobian + approximation. If the step size is smaller than this, optimization + is terminated as successful. If omitted, not used. + tol_norm : function(vector) -> scalar, optional + Norm to use in convergence check. Default is the maximum norm. + line_search : {None, 'armijo' (default), 'wolfe'}, optional + Which type of a line search to use to determine the step size in + the direction given by the Jacobian approximation. Defaults to + 'armijo'. + jac_options : dict, optional + Options for the respective Jacobian approximation. + + alpha : float, optional + Initial Jacobian approximation is (-1/alpha). + alphamax : float, optional + The entries of the diagonal Jacobian are kept in the range + ``[alpha, alphamax]``. + """ + pass + +def _root_krylov_doc(): + """ + Options + ------- + nit : int, optional + Number of iterations to make. If omitted (default), make as many + as required to meet tolerances. + disp : bool, optional + Print status to stdout on every iteration. + maxiter : int, optional + Maximum number of iterations to make. + ftol : float, optional + Relative tolerance for the residual. If omitted, not used. + fatol : float, optional + Absolute tolerance (in max-norm) for the residual. + If omitted, default is 6e-6. + xtol : float, optional + Relative minimum step size. If omitted, not used. + xatol : float, optional + Absolute minimum step size, as determined from the Jacobian + approximation. If the step size is smaller than this, optimization + is terminated as successful. If omitted, not used. + tol_norm : function(vector) -> scalar, optional + Norm to use in convergence check. Default is the maximum norm. + line_search : {None, 'armijo' (default), 'wolfe'}, optional + Which type of a line search to use to determine the step size in + the direction given by the Jacobian approximation. Defaults to + 'armijo'. + jac_options : dict, optional + Options for the respective Jacobian approximation. + + rdiff : float, optional + Relative step size to use in numerical differentiation. + method : str or callable, optional + Krylov method to use to approximate the Jacobian. Can be a string, + or a function implementing the same interface as the iterative + solvers in `scipy.sparse.linalg`. If a string, needs to be one of: + ``'lgmres'``, ``'gmres'``, ``'bicgstab'``, ``'cgs'``, ``'minres'``, + ``'tfqmr'``. + + The default is `scipy.sparse.linalg.lgmres`. + inner_M : LinearOperator or InverseJacobian + Preconditioner for the inner Krylov iteration. + Note that you can use also inverse Jacobians as (adaptive) + preconditioners. For example, + + >>> jac = BroydenFirst() + >>> kjac = KrylovJacobian(inner_M=jac.inverse). + + If the preconditioner has a method named 'update', it will + be called as ``update(x, f)`` after each nonlinear step, + with ``x`` giving the current point, and ``f`` the current + function value. + inner_tol, inner_maxiter, ... + Parameters to pass on to the "inner" Krylov solver. + See `scipy.sparse.linalg.gmres` for details. + outer_k : int, optional + Size of the subspace kept across LGMRES nonlinear + iterations. + + See `scipy.sparse.linalg.lgmres` for details. + """ + pass diff --git a/llava_next/lib/python3.10/site-packages/scipy/optimize/_root_scalar.py b/llava_next/lib/python3.10/site-packages/scipy/optimize/_root_scalar.py new file mode 100644 index 0000000000000000000000000000000000000000..550098bbe677825b34e19aec29e340143b3522cc --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/scipy/optimize/_root_scalar.py @@ -0,0 +1,525 @@ +""" +Unified interfaces to root finding algorithms for real or complex +scalar functions. + +Functions +--------- +- root : find a root of a scalar function. +""" +import numpy as np + +from . import _zeros_py as optzeros +from ._numdiff import approx_derivative + +__all__ = ['root_scalar'] + +ROOT_SCALAR_METHODS = ['bisect', 'brentq', 'brenth', 'ridder', 'toms748', + 'newton', 'secant', 'halley'] + + +class MemoizeDer: + """Decorator that caches the value and derivative(s) of function each + time it is called. + + This is a simplistic memoizer that calls and caches a single value + of `f(x, *args)`. + It assumes that `args` does not change between invocations. + It supports the use case of a root-finder where `args` is fixed, + `x` changes, and only rarely, if at all, does x assume the same value + more than once.""" + def __init__(self, fun): + self.fun = fun + self.vals = None + self.x = None + self.n_calls = 0 + + def __call__(self, x, *args): + r"""Calculate f or use cached value if available""" + # Derivative may be requested before the function itself, always check + if self.vals is None or x != self.x: + fg = self.fun(x, *args) + self.x = x + self.n_calls += 1 + self.vals = fg[:] + return self.vals[0] + + def fprime(self, x, *args): + r"""Calculate f' or use a cached value if available""" + if self.vals is None or x != self.x: + self(x, *args) + return self.vals[1] + + def fprime2(self, x, *args): + r"""Calculate f'' or use a cached value if available""" + if self.vals is None or x != self.x: + self(x, *args) + return self.vals[2] + + def ncalls(self): + return self.n_calls + + +def root_scalar(f, args=(), method=None, bracket=None, + fprime=None, fprime2=None, + x0=None, x1=None, + xtol=None, rtol=None, maxiter=None, + options=None): + """ + Find a root of a scalar function. + + Parameters + ---------- + f : callable + A function to find a root of. + args : tuple, optional + Extra arguments passed to the objective function and its derivative(s). + method : str, optional + Type of solver. Should be one of + + - 'bisect' :ref:`(see here) ` + - 'brentq' :ref:`(see here) ` + - 'brenth' :ref:`(see here) ` + - 'ridder' :ref:`(see here) ` + - 'toms748' :ref:`(see here) ` + - 'newton' :ref:`(see here) ` + - 'secant' :ref:`(see here) ` + - 'halley' :ref:`(see here) ` + + bracket: A sequence of 2 floats, optional + An interval bracketing a root. `f(x, *args)` must have different + signs at the two endpoints. + x0 : float, optional + Initial guess. + x1 : float, optional + A second guess. + fprime : bool or callable, optional + If `fprime` is a boolean and is True, `f` is assumed to return the + value of the objective function and of the derivative. + `fprime` can also be a callable returning the derivative of `f`. In + this case, it must accept the same arguments as `f`. + fprime2 : bool or callable, optional + If `fprime2` is a boolean and is True, `f` is assumed to return the + value of the objective function and of the + first and second derivatives. + `fprime2` can also be a callable returning the second derivative of `f`. + In this case, it must accept the same arguments as `f`. + xtol : float, optional + Tolerance (absolute) for termination. + rtol : float, optional + Tolerance (relative) for termination. + maxiter : int, optional + Maximum number of iterations. + options : dict, optional + A dictionary of solver options. E.g., ``k``, see + :obj:`show_options()` for details. + + Returns + ------- + sol : RootResults + The solution represented as a ``RootResults`` object. + Important attributes are: ``root`` the solution , ``converged`` a + boolean flag indicating if the algorithm exited successfully and + ``flag`` which describes the cause of the termination. See + `RootResults` for a description of other attributes. + + See also + -------- + show_options : Additional options accepted by the solvers + root : Find a root of a vector function. + + Notes + ----- + This section describes the available solvers that can be selected by the + 'method' parameter. + + The default is to use the best method available for the situation + presented. + If a bracket is provided, it may use one of the bracketing methods. + If a derivative and an initial value are specified, it may + select one of the derivative-based methods. + If no method is judged applicable, it will raise an Exception. + + Arguments for each method are as follows (x=required, o=optional). + + +-----------------------------------------------+---+------+---------+----+----+--------+---------+------+------+---------+---------+ + | method | f | args | bracket | x0 | x1 | fprime | fprime2 | xtol | rtol | maxiter | options | + +===============================================+===+======+=========+====+====+========+=========+======+======+=========+=========+ + | :ref:`bisect ` | x | o | x | | | | | o | o | o | o | + +-----------------------------------------------+---+------+---------+----+----+--------+---------+------+------+---------+---------+ + | :ref:`brentq ` | x | o | x | | | | | o | o | o | o | + +-----------------------------------------------+---+------+---------+----+----+--------+---------+------+------+---------+---------+ + | :ref:`brenth ` | x | o | x | | | | | o | o | o | o | + +-----------------------------------------------+---+------+---------+----+----+--------+---------+------+------+---------+---------+ + | :ref:`ridder ` | x | o | x | | | | | o | o | o | o | + +-----------------------------------------------+---+------+---------+----+----+--------+---------+------+------+---------+---------+ + | :ref:`toms748 ` | x | o | x | | | | | o | o | o | o | + +-----------------------------------------------+---+------+---------+----+----+--------+---------+------+------+---------+---------+ + | :ref:`secant ` | x | o | | x | o | | | o | o | o | o | + +-----------------------------------------------+---+------+---------+----+----+--------+---------+------+------+---------+---------+ + | :ref:`newton ` | x | o | | x | | o | | o | o | o | o | + +-----------------------------------------------+---+------+---------+----+----+--------+---------+------+------+---------+---------+ + | :ref:`halley ` | x | o | | x | | x | x | o | o | o | o | + +-----------------------------------------------+---+------+---------+----+----+--------+---------+------+------+---------+---------+ + + Examples + -------- + + Find the root of a simple cubic + + >>> from scipy import optimize + >>> def f(x): + ... return (x**3 - 1) # only one real root at x = 1 + + >>> def fprime(x): + ... return 3*x**2 + + The `brentq` method takes as input a bracket + + >>> sol = optimize.root_scalar(f, bracket=[0, 3], method='brentq') + >>> sol.root, sol.iterations, sol.function_calls + (1.0, 10, 11) + + The `newton` method takes as input a single point and uses the + derivative(s). + + >>> sol = optimize.root_scalar(f, x0=0.2, fprime=fprime, method='newton') + >>> sol.root, sol.iterations, sol.function_calls + (1.0, 11, 22) + + The function can provide the value and derivative(s) in a single call. + + >>> def f_p_pp(x): + ... return (x**3 - 1), 3*x**2, 6*x + + >>> sol = optimize.root_scalar( + ... f_p_pp, x0=0.2, fprime=True, method='newton' + ... ) + >>> sol.root, sol.iterations, sol.function_calls + (1.0, 11, 11) + + >>> sol = optimize.root_scalar( + ... f_p_pp, x0=0.2, fprime=True, fprime2=True, method='halley' + ... ) + >>> sol.root, sol.iterations, sol.function_calls + (1.0, 7, 8) + + + """ # noqa: E501 + if not isinstance(args, tuple): + args = (args,) + + if options is None: + options = {} + + # fun also returns the derivative(s) + is_memoized = False + if fprime2 is not None and not callable(fprime2): + if bool(fprime2): + f = MemoizeDer(f) + is_memoized = True + fprime2 = f.fprime2 + fprime = f.fprime + else: + fprime2 = None + if fprime is not None and not callable(fprime): + if bool(fprime): + f = MemoizeDer(f) + is_memoized = True + fprime = f.fprime + else: + fprime = None + + # respect solver-specific default tolerances - only pass in if actually set + kwargs = {} + for k in ['xtol', 'rtol', 'maxiter']: + v = locals().get(k) + if v is not None: + kwargs[k] = v + + # Set any solver-specific options + if options: + kwargs.update(options) + # Always request full_output from the underlying method as _root_scalar + # always returns a RootResults object + kwargs.update(full_output=True, disp=False) + + # Pick a method if not specified. + # Use the "best" method available for the situation. + if not method: + if bracket: + method = 'brentq' + elif x0 is not None: + if fprime: + if fprime2: + method = 'halley' + else: + method = 'newton' + elif x1 is not None: + method = 'secant' + else: + method = 'newton' + if not method: + raise ValueError('Unable to select a solver as neither bracket ' + 'nor starting point provided.') + + meth = method.lower() + map2underlying = {'halley': 'newton', 'secant': 'newton'} + + try: + methodc = getattr(optzeros, map2underlying.get(meth, meth)) + except AttributeError as e: + raise ValueError('Unknown solver %s' % meth) from e + + if meth in ['bisect', 'ridder', 'brentq', 'brenth', 'toms748']: + if not isinstance(bracket, (list, tuple, np.ndarray)): + raise ValueError('Bracket needed for %s' % method) + + a, b = bracket[:2] + try: + r, sol = methodc(f, a, b, args=args, **kwargs) + except ValueError as e: + # gh-17622 fixed some bugs in low-level solvers by raising an error + # (rather than returning incorrect results) when the callable + # returns a NaN. It did so by wrapping the callable rather than + # modifying compiled code, so the iteration count is not available. + if hasattr(e, "_x"): + sol = optzeros.RootResults(root=e._x, + iterations=np.nan, + function_calls=e._function_calls, + flag=str(e), method=method) + else: + raise + + elif meth in ['secant']: + if x0 is None: + raise ValueError('x0 must not be None for %s' % method) + if 'xtol' in kwargs: + kwargs['tol'] = kwargs.pop('xtol') + r, sol = methodc(f, x0, args=args, fprime=None, fprime2=None, + x1=x1, **kwargs) + elif meth in ['newton']: + if x0 is None: + raise ValueError('x0 must not be None for %s' % method) + if not fprime: + # approximate fprime with finite differences + + def fprime(x, *args): + # `root_scalar` doesn't actually seem to support vectorized + # use of `newton`. In that case, `approx_derivative` will + # always get scalar input. Nonetheless, it always returns an + # array, so we extract the element to produce scalar output. + return approx_derivative(f, x, method='2-point', args=args)[0] + + if 'xtol' in kwargs: + kwargs['tol'] = kwargs.pop('xtol') + r, sol = methodc(f, x0, args=args, fprime=fprime, fprime2=None, + **kwargs) + elif meth in ['halley']: + if x0 is None: + raise ValueError('x0 must not be None for %s' % method) + if not fprime: + raise ValueError('fprime must be specified for %s' % method) + if not fprime2: + raise ValueError('fprime2 must be specified for %s' % method) + if 'xtol' in kwargs: + kwargs['tol'] = kwargs.pop('xtol') + r, sol = methodc(f, x0, args=args, fprime=fprime, fprime2=fprime2, **kwargs) + else: + raise ValueError('Unknown solver %s' % method) + + if is_memoized: + # Replace the function_calls count with the memoized count. + # Avoids double and triple-counting. + n_calls = f.n_calls + sol.function_calls = n_calls + + return sol + + +def _root_scalar_brentq_doc(): + r""" + Options + ------- + args : tuple, optional + Extra arguments passed to the objective function. + bracket: A sequence of 2 floats, optional + An interval bracketing a root. `f(x, *args)` must have different + signs at the two endpoints. + xtol : float, optional + Tolerance (absolute) for termination. + rtol : float, optional + Tolerance (relative) for termination. + maxiter : int, optional + Maximum number of iterations. + options: dict, optional + Specifies any method-specific options not covered above + + """ + pass + + +def _root_scalar_brenth_doc(): + r""" + Options + ------- + args : tuple, optional + Extra arguments passed to the objective function. + bracket: A sequence of 2 floats, optional + An interval bracketing a root. `f(x, *args)` must have different + signs at the two endpoints. + xtol : float, optional + Tolerance (absolute) for termination. + rtol : float, optional + Tolerance (relative) for termination. + maxiter : int, optional + Maximum number of iterations. + options: dict, optional + Specifies any method-specific options not covered above. + + """ + pass + +def _root_scalar_toms748_doc(): + r""" + Options + ------- + args : tuple, optional + Extra arguments passed to the objective function. + bracket: A sequence of 2 floats, optional + An interval bracketing a root. `f(x, *args)` must have different + signs at the two endpoints. + xtol : float, optional + Tolerance (absolute) for termination. + rtol : float, optional + Tolerance (relative) for termination. + maxiter : int, optional + Maximum number of iterations. + options: dict, optional + Specifies any method-specific options not covered above. + + """ + pass + + +def _root_scalar_secant_doc(): + r""" + Options + ------- + args : tuple, optional + Extra arguments passed to the objective function. + xtol : float, optional + Tolerance (absolute) for termination. + rtol : float, optional + Tolerance (relative) for termination. + maxiter : int, optional + Maximum number of iterations. + x0 : float, required + Initial guess. + x1 : float, required + A second guess. + options: dict, optional + Specifies any method-specific options not covered above. + + """ + pass + + +def _root_scalar_newton_doc(): + r""" + Options + ------- + args : tuple, optional + Extra arguments passed to the objective function and its derivative. + xtol : float, optional + Tolerance (absolute) for termination. + rtol : float, optional + Tolerance (relative) for termination. + maxiter : int, optional + Maximum number of iterations. + x0 : float, required + Initial guess. + fprime : bool or callable, optional + If `fprime` is a boolean and is True, `f` is assumed to return the + value of derivative along with the objective function. + `fprime` can also be a callable returning the derivative of `f`. In + this case, it must accept the same arguments as `f`. + options: dict, optional + Specifies any method-specific options not covered above. + + """ + pass + + +def _root_scalar_halley_doc(): + r""" + Options + ------- + args : tuple, optional + Extra arguments passed to the objective function and its derivatives. + xtol : float, optional + Tolerance (absolute) for termination. + rtol : float, optional + Tolerance (relative) for termination. + maxiter : int, optional + Maximum number of iterations. + x0 : float, required + Initial guess. + fprime : bool or callable, required + If `fprime` is a boolean and is True, `f` is assumed to return the + value of derivative along with the objective function. + `fprime` can also be a callable returning the derivative of `f`. In + this case, it must accept the same arguments as `f`. + fprime2 : bool or callable, required + If `fprime2` is a boolean and is True, `f` is assumed to return the + value of 1st and 2nd derivatives along with the objective function. + `fprime2` can also be a callable returning the 2nd derivative of `f`. + In this case, it must accept the same arguments as `f`. + options: dict, optional + Specifies any method-specific options not covered above. + + """ + pass + + +def _root_scalar_ridder_doc(): + r""" + Options + ------- + args : tuple, optional + Extra arguments passed to the objective function. + bracket: A sequence of 2 floats, optional + An interval bracketing a root. `f(x, *args)` must have different + signs at the two endpoints. + xtol : float, optional + Tolerance (absolute) for termination. + rtol : float, optional + Tolerance (relative) for termination. + maxiter : int, optional + Maximum number of iterations. + options: dict, optional + Specifies any method-specific options not covered above. + + """ + pass + + +def _root_scalar_bisect_doc(): + r""" + Options + ------- + args : tuple, optional + Extra arguments passed to the objective function. + bracket: A sequence of 2 floats, optional + An interval bracketing a root. `f(x, *args)` must have different + signs at the two endpoints. + xtol : float, optional + Tolerance (absolute) for termination. + rtol : float, optional + Tolerance (relative) for termination. + maxiter : int, optional + Maximum number of iterations. + options: dict, optional + Specifies any method-specific options not covered above. + + """ + pass diff --git a/llava_next/lib/python3.10/site-packages/scipy/optimize/_shgo.py b/llava_next/lib/python3.10/site-packages/scipy/optimize/_shgo.py new file mode 100644 index 0000000000000000000000000000000000000000..4dce006dcbcac78513451441e067f027016b6f5b --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/scipy/optimize/_shgo.py @@ -0,0 +1,1598 @@ +"""shgo: The simplicial homology global optimisation algorithm.""" +from collections import namedtuple +import time +import logging +import warnings +import sys + +import numpy as np + +from scipy import spatial +from scipy.optimize import OptimizeResult, minimize, Bounds +from scipy.optimize._optimize import MemoizeJac +from scipy.optimize._constraints import new_bounds_to_old +from scipy.optimize._minimize import standardize_constraints +from scipy._lib._util import _FunctionWrapper + +from scipy.optimize._shgo_lib._complex import Complex + +__all__ = ['shgo'] + + +def shgo( + func, bounds, args=(), constraints=None, n=100, iters=1, callback=None, + minimizer_kwargs=None, options=None, sampling_method='simplicial', *, + workers=1 +): + """ + Finds the global minimum of a function using SHG optimization. + + SHGO stands for "simplicial homology global optimization". + + Parameters + ---------- + func : callable + The objective function to be minimized. Must be in the form + ``f(x, *args)``, where ``x`` is the argument in the form of a 1-D array + and ``args`` is a tuple of any additional fixed parameters needed to + completely specify the function. + bounds : sequence or `Bounds` + Bounds for variables. There are two ways to specify the bounds: + + 1. Instance of `Bounds` class. + 2. Sequence of ``(min, max)`` pairs for each element in `x`. + + args : tuple, optional + Any additional fixed parameters needed to completely specify the + objective function. + constraints : {Constraint, dict} or List of {Constraint, dict}, optional + Constraints definition. Only for COBYLA, COBYQA, SLSQP and trust-constr. + See the tutorial [5]_ for further details on specifying constraints. + + .. note:: + + Only COBYLA, COBYQA, SLSQP, and trust-constr local minimize methods + currently support constraint arguments. If the ``constraints`` + sequence used in the local optimization problem is not defined in + ``minimizer_kwargs`` and a constrained method is used then the + global ``constraints`` will be used. + (Defining a ``constraints`` sequence in ``minimizer_kwargs`` + means that ``constraints`` will not be added so if equality + constraints and so forth need to be added then the inequality + functions in ``constraints`` need to be added to + ``minimizer_kwargs`` too). + COBYLA only supports inequality constraints. + + .. versionchanged:: 1.11.0 + + ``constraints`` accepts `NonlinearConstraint`, `LinearConstraint`. + + n : int, optional + Number of sampling points used in the construction of the simplicial + complex. For the default ``simplicial`` sampling method 2**dim + 1 + sampling points are generated instead of the default `n=100`. For all + other specified values `n` sampling points are generated. For + ``sobol``, ``halton`` and other arbitrary `sampling_methods` `n=100` or + another specified number of sampling points are generated. + iters : int, optional + Number of iterations used in the construction of the simplicial + complex. Default is 1. + callback : callable, optional + Called after each iteration, as ``callback(xk)``, where ``xk`` is the + current parameter vector. + minimizer_kwargs : dict, optional + Extra keyword arguments to be passed to the minimizer + ``scipy.optimize.minimize`` Some important options could be: + + * method : str + The minimization method. If not given, chosen to be one of + BFGS, L-BFGS-B, SLSQP, depending on whether or not the + problem has constraints or bounds. + * args : tuple + Extra arguments passed to the objective function (``func``) and + its derivatives (Jacobian, Hessian). + * options : dict, optional + Note that by default the tolerance is specified as + ``{ftol: 1e-12}`` + + options : dict, optional + A dictionary of solver options. Many of the options specified for the + global routine are also passed to the scipy.optimize.minimize routine. + The options that are also passed to the local routine are marked with + "(L)". + + Stopping criteria, the algorithm will terminate if any of the specified + criteria are met. However, the default algorithm does not require any + to be specified: + + * maxfev : int (L) + Maximum number of function evaluations in the feasible domain. + (Note only methods that support this option will terminate + the routine at precisely exact specified value. Otherwise the + criterion will only terminate during a global iteration) + * f_min + Specify the minimum objective function value, if it is known. + * f_tol : float + Precision goal for the value of f in the stopping + criterion. Note that the global routine will also + terminate if a sampling point in the global routine is + within this tolerance. + * maxiter : int + Maximum number of iterations to perform. + * maxev : int + Maximum number of sampling evaluations to perform (includes + searching in infeasible points). + * maxtime : float + Maximum processing runtime allowed + * minhgrd : int + Minimum homology group rank differential. The homology group of the + objective function is calculated (approximately) during every + iteration. The rank of this group has a one-to-one correspondence + with the number of locally convex subdomains in the objective + function (after adequate sampling points each of these subdomains + contain a unique global minimum). If the difference in the hgr is 0 + between iterations for ``maxhgrd`` specified iterations the + algorithm will terminate. + + Objective function knowledge: + + * symmetry : list or bool + Specify if the objective function contains symmetric variables. + The search space (and therefore performance) is decreased by up to + O(n!) times in the fully symmetric case. If `True` is specified + then all variables will be set symmetric to the first variable. + Default + is set to False. + + E.g. f(x) = (x_1 + x_2 + x_3) + (x_4)**2 + (x_5)**2 + (x_6)**2 + + In this equation x_2 and x_3 are symmetric to x_1, while x_5 and + x_6 are symmetric to x_4, this can be specified to the solver as: + + symmetry = [0, # Variable 1 + 0, # symmetric to variable 1 + 0, # symmetric to variable 1 + 3, # Variable 4 + 3, # symmetric to variable 4 + 3, # symmetric to variable 4 + ] + + * jac : bool or callable, optional + Jacobian (gradient) of objective function. Only for CG, BFGS, + Newton-CG, L-BFGS-B, TNC, SLSQP, dogleg, trust-ncg. If ``jac`` is a + boolean and is True, ``fun`` is assumed to return the gradient + along with the objective function. If False, the gradient will be + estimated numerically. ``jac`` can also be a callable returning the + gradient of the objective. In this case, it must accept the same + arguments as ``fun``. (Passed to `scipy.optimize.minimize` + automatically) + + * hess, hessp : callable, optional + Hessian (matrix of second-order derivatives) of objective function + or Hessian of objective function times an arbitrary vector p. + Only for Newton-CG, dogleg, trust-ncg. Only one of ``hessp`` or + ``hess`` needs to be given. If ``hess`` is provided, then + ``hessp`` will be ignored. If neither ``hess`` nor ``hessp`` is + provided, then the Hessian product will be approximated using + finite differences on ``jac``. ``hessp`` must compute the Hessian + times an arbitrary vector. (Passed to `scipy.optimize.minimize` + automatically) + + Algorithm settings: + + * minimize_every_iter : bool + If True then promising global sampling points will be passed to a + local minimization routine every iteration. If True then only the + final minimizer pool will be run. Defaults to True. + * local_iter : int + Only evaluate a few of the best minimizer pool candidates every + iteration. If False all potential points are passed to the local + minimization routine. + * infty_constraints : bool + If True then any sampling points generated which are outside will + the feasible domain will be saved and given an objective function + value of ``inf``. If False then these points will be discarded. + Using this functionality could lead to higher performance with + respect to function evaluations before the global minimum is found, + specifying False will use less memory at the cost of a slight + decrease in performance. Defaults to True. + + Feedback: + + * disp : bool (L) + Set to True to print convergence messages. + + sampling_method : str or function, optional + Current built in sampling method options are ``halton``, ``sobol`` and + ``simplicial``. The default ``simplicial`` provides + the theoretical guarantee of convergence to the global minimum in + finite time. ``halton`` and ``sobol`` method are faster in terms of + sampling point generation at the cost of the loss of + guaranteed convergence. It is more appropriate for most "easier" + problems where the convergence is relatively fast. + User defined sampling functions must accept two arguments of ``n`` + sampling points of dimension ``dim`` per call and output an array of + sampling points with shape `n x dim`. + + workers : int or map-like callable, optional + Sample and run the local serial minimizations in parallel. + Supply -1 to use all available CPU cores, or an int to use + that many Processes (uses `multiprocessing.Pool `). + + Alternatively supply a map-like callable, such as + `multiprocessing.Pool.map` for parallel evaluation. + This evaluation is carried out as ``workers(func, iterable)``. + Requires that `func` be pickleable. + + .. versionadded:: 1.11.0 + + Returns + ------- + res : OptimizeResult + The optimization result represented as a `OptimizeResult` object. + Important attributes are: + ``x`` the solution array corresponding to the global minimum, + ``fun`` the function output at the global solution, + ``xl`` an ordered list of local minima solutions, + ``funl`` the function output at the corresponding local solutions, + ``success`` a Boolean flag indicating if the optimizer exited + successfully, + ``message`` which describes the cause of the termination, + ``nfev`` the total number of objective function evaluations including + the sampling calls, + ``nlfev`` the total number of objective function evaluations + culminating from all local search optimizations, + ``nit`` number of iterations performed by the global routine. + + Notes + ----- + Global optimization using simplicial homology global optimization [1]_. + Appropriate for solving general purpose NLP and blackbox optimization + problems to global optimality (low-dimensional problems). + + In general, the optimization problems are of the form:: + + minimize f(x) subject to + + g_i(x) >= 0, i = 1,...,m + h_j(x) = 0, j = 1,...,p + + where x is a vector of one or more variables. ``f(x)`` is the objective + function ``R^n -> R``, ``g_i(x)`` are the inequality constraints, and + ``h_j(x)`` are the equality constraints. + + Optionally, the lower and upper bounds for each element in x can also be + specified using the `bounds` argument. + + While most of the theoretical advantages of SHGO are only proven for when + ``f(x)`` is a Lipschitz smooth function, the algorithm is also proven to + converge to the global optimum for the more general case where ``f(x)`` is + non-continuous, non-convex and non-smooth, if the default sampling method + is used [1]_. + + The local search method may be specified using the ``minimizer_kwargs`` + parameter which is passed on to ``scipy.optimize.minimize``. By default, + the ``SLSQP`` method is used. In general, it is recommended to use the + ``SLSQP``, ``COBYLA``, or ``COBYQA`` local minimization if inequality + constraints are defined for the problem since the other methods do not use + constraints. + + The ``halton`` and ``sobol`` method points are generated using + `scipy.stats.qmc`. Any other QMC method could be used. + + References + ---------- + .. [1] Endres, SC, Sandrock, C, Focke, WW (2018) "A simplicial homology + algorithm for lipschitz optimisation", Journal of Global + Optimization. + .. [2] Joe, SW and Kuo, FY (2008) "Constructing Sobol' sequences with + better two-dimensional projections", SIAM J. Sci. Comput. 30, + 2635-2654. + .. [3] Hock, W and Schittkowski, K (1981) "Test examples for nonlinear + programming codes", Lecture Notes in Economics and Mathematical + Systems, 187. Springer-Verlag, New York. + http://www.ai7.uni-bayreuth.de/test_problem_coll.pdf + .. [4] Wales, DJ (2015) "Perspective: Insight into reaction coordinates and + dynamics from the potential energy landscape", + Journal of Chemical Physics, 142(13), 2015. + .. [5] https://docs.scipy.org/doc/scipy/tutorial/optimize.html#constrained-minimization-of-multivariate-scalar-functions-minimize + + Examples + -------- + First consider the problem of minimizing the Rosenbrock function, `rosen`: + + >>> from scipy.optimize import rosen, shgo + >>> bounds = [(0,2), (0, 2), (0, 2), (0, 2), (0, 2)] + >>> result = shgo(rosen, bounds) + >>> result.x, result.fun + (array([1., 1., 1., 1., 1.]), 2.920392374190081e-18) + + Note that bounds determine the dimensionality of the objective + function and is therefore a required input, however you can specify + empty bounds using ``None`` or objects like ``np.inf`` which will be + converted to large float numbers. + + >>> bounds = [(None, None), ]*4 + >>> result = shgo(rosen, bounds) + >>> result.x + array([0.99999851, 0.99999704, 0.99999411, 0.9999882 ]) + + Next, we consider the Eggholder function, a problem with several local + minima and one global minimum. We will demonstrate the use of arguments and + the capabilities of `shgo`. + (https://en.wikipedia.org/wiki/Test_functions_for_optimization) + + >>> import numpy as np + >>> def eggholder(x): + ... return (-(x[1] + 47.0) + ... * np.sin(np.sqrt(abs(x[0]/2.0 + (x[1] + 47.0)))) + ... - x[0] * np.sin(np.sqrt(abs(x[0] - (x[1] + 47.0)))) + ... ) + ... + >>> bounds = [(-512, 512), (-512, 512)] + + `shgo` has built-in low discrepancy sampling sequences. First, we will + input 64 initial sampling points of the *Sobol'* sequence: + + >>> result = shgo(eggholder, bounds, n=64, sampling_method='sobol') + >>> result.x, result.fun + (array([512. , 404.23180824]), -959.6406627208397) + + `shgo` also has a return for any other local minima that was found, these + can be called using: + + >>> result.xl + array([[ 512. , 404.23180824], + [ 283.0759062 , -487.12565635], + [-294.66820039, -462.01964031], + [-105.87688911, 423.15323845], + [-242.97926 , 274.38030925], + [-506.25823477, 6.3131022 ], + [-408.71980731, -156.10116949], + [ 150.23207937, 301.31376595], + [ 91.00920901, -391.283763 ], + [ 202.89662724, -269.38043241], + [ 361.66623976, -106.96493868], + [-219.40612786, -244.06020508]]) + + >>> result.funl + array([-959.64066272, -718.16745962, -704.80659592, -565.99778097, + -559.78685655, -557.36868733, -507.87385942, -493.9605115 , + -426.48799655, -421.15571437, -419.31194957, -410.98477763]) + + These results are useful in applications where there are many global minima + and the values of other global minima are desired or where the local minima + can provide insight into the system (for example morphologies + in physical chemistry [4]_). + + If we want to find a larger number of local minima, we can increase the + number of sampling points or the number of iterations. We'll increase the + number of sampling points to 64 and the number of iterations from the + default of 1 to 3. Using ``simplicial`` this would have given us + 64 x 3 = 192 initial sampling points. + + >>> result_2 = shgo(eggholder, + ... bounds, n=64, iters=3, sampling_method='sobol') + >>> len(result.xl), len(result_2.xl) + (12, 23) + + Note the difference between, e.g., ``n=192, iters=1`` and ``n=64, + iters=3``. + In the first case the promising points contained in the minimiser pool + are processed only once. In the latter case it is processed every 64 + sampling points for a total of 3 times. + + To demonstrate solving problems with non-linear constraints consider the + following example from Hock and Schittkowski problem 73 (cattle-feed) + [3]_:: + + minimize: f = 24.55 * x_1 + 26.75 * x_2 + 39 * x_3 + 40.50 * x_4 + + subject to: 2.3 * x_1 + 5.6 * x_2 + 11.1 * x_3 + 1.3 * x_4 - 5 >= 0, + + 12 * x_1 + 11.9 * x_2 + 41.8 * x_3 + 52.1 * x_4 - 21 + -1.645 * sqrt(0.28 * x_1**2 + 0.19 * x_2**2 + + 20.5 * x_3**2 + 0.62 * x_4**2) >= 0, + + x_1 + x_2 + x_3 + x_4 - 1 == 0, + + 1 >= x_i >= 0 for all i + + The approximate answer given in [3]_ is:: + + f([0.6355216, -0.12e-11, 0.3127019, 0.05177655]) = 29.894378 + + >>> def f(x): # (cattle-feed) + ... return 24.55*x[0] + 26.75*x[1] + 39*x[2] + 40.50*x[3] + ... + >>> def g1(x): + ... return 2.3*x[0] + 5.6*x[1] + 11.1*x[2] + 1.3*x[3] - 5 # >=0 + ... + >>> def g2(x): + ... return (12*x[0] + 11.9*x[1] +41.8*x[2] + 52.1*x[3] - 21 + ... - 1.645 * np.sqrt(0.28*x[0]**2 + 0.19*x[1]**2 + ... + 20.5*x[2]**2 + 0.62*x[3]**2) + ... ) # >=0 + ... + >>> def h1(x): + ... return x[0] + x[1] + x[2] + x[3] - 1 # == 0 + ... + >>> cons = ({'type': 'ineq', 'fun': g1}, + ... {'type': 'ineq', 'fun': g2}, + ... {'type': 'eq', 'fun': h1}) + >>> bounds = [(0, 1.0),]*4 + >>> res = shgo(f, bounds, n=150, constraints=cons) + >>> res + message: Optimization terminated successfully. + success: True + fun: 29.894378159142136 + funl: [ 2.989e+01] + x: [ 6.355e-01 1.137e-13 3.127e-01 5.178e-02] # may vary + xl: [[ 6.355e-01 1.137e-13 3.127e-01 5.178e-02]] # may vary + nit: 1 + nfev: 142 # may vary + nlfev: 35 # may vary + nljev: 5 + nlhev: 0 + + >>> g1(res.x), g2(res.x), h1(res.x) + (-5.062616992290714e-14, -2.9594104944408173e-12, 0.0) + + """ + # if necessary, convert bounds class to old bounds + if isinstance(bounds, Bounds): + bounds = new_bounds_to_old(bounds.lb, bounds.ub, len(bounds.lb)) + + # Initiate SHGO class + # use in context manager to make sure that any parallelization + # resources are freed. + with SHGO(func, bounds, args=args, constraints=constraints, n=n, + iters=iters, callback=callback, + minimizer_kwargs=minimizer_kwargs, + options=options, sampling_method=sampling_method, + workers=workers) as shc: + # Run the algorithm, process results and test success + shc.iterate_all() + + if not shc.break_routine: + if shc.disp: + logging.info("Successfully completed construction of complex.") + + # Test post iterations success + if len(shc.LMC.xl_maps) == 0: + # If sampling failed to find pool, return lowest sampled point + # with a warning + shc.find_lowest_vertex() + shc.break_routine = True + shc.fail_routine(mes="Failed to find a feasible minimizer point. " + f"Lowest sampling point = {shc.f_lowest}") + shc.res.fun = shc.f_lowest + shc.res.x = shc.x_lowest + shc.res.nfev = shc.fn + shc.res.tnev = shc.n_sampled + else: + # Test that the optimal solutions do not violate any constraints + pass # TODO + + # Confirm the routine ran successfully + if not shc.break_routine: + shc.res.message = 'Optimization terminated successfully.' + shc.res.success = True + + # Return the final results + return shc.res + + +class SHGO: + def __init__(self, func, bounds, args=(), constraints=None, n=None, + iters=None, callback=None, minimizer_kwargs=None, + options=None, sampling_method='simplicial', workers=1): + from scipy.stats import qmc + # Input checks + methods = ['halton', 'sobol', 'simplicial'] + if isinstance(sampling_method, str) and sampling_method not in methods: + raise ValueError(("Unknown sampling_method specified." + " Valid methods: {}").format(', '.join(methods))) + + # Split obj func if given with Jac + try: + if ((minimizer_kwargs['jac'] is True) and + (not callable(minimizer_kwargs['jac']))): + self.func = MemoizeJac(func) + jac = self.func.derivative + minimizer_kwargs['jac'] = jac + func = self.func # .fun + else: + self.func = func # Normal definition of objective function + except (TypeError, KeyError): + self.func = func # Normal definition of objective function + + # Initiate class + self.func = _FunctionWrapper(func, args) + self.bounds = bounds + self.args = args + self.callback = callback + + # Bounds + abound = np.array(bounds, float) + self.dim = np.shape(abound)[0] # Dimensionality of problem + + # Set none finite values to large floats + infind = ~np.isfinite(abound) + abound[infind[:, 0], 0] = -1e50 + abound[infind[:, 1], 1] = 1e50 + + # Check if bounds are correctly specified + bnderr = abound[:, 0] > abound[:, 1] + if bnderr.any(): + raise ValueError('Error: lb > ub in bounds {}.' + .format(', '.join(str(b) for b in bnderr))) + + self.bounds = abound + + # Constraints + # Process constraint dict sequence: + self.constraints = constraints + if constraints is not None: + self.min_cons = constraints + self.g_cons = [] + self.g_args = [] + + # shgo internals deals with old-style constraints + # self.constraints is used to create Complex, so need + # to be stored internally in old-style. + # `minimize` takes care of normalising these constraints + # for slsqp/cobyla/cobyqa/trust-constr. + self.constraints = standardize_constraints( + constraints, + np.empty(self.dim, float), + 'old' + ) + for cons in self.constraints: + if cons['type'] in ('ineq'): + self.g_cons.append(cons['fun']) + try: + self.g_args.append(cons['args']) + except KeyError: + self.g_args.append(()) + self.g_cons = tuple(self.g_cons) + self.g_args = tuple(self.g_args) + else: + self.g_cons = None + self.g_args = None + + # Define local minimization keyword arguments + # Start with defaults + self.minimizer_kwargs = {'method': 'SLSQP', + 'bounds': self.bounds, + 'options': {}, + 'callback': self.callback + } + if minimizer_kwargs is not None: + # Overwrite with supplied values + self.minimizer_kwargs.update(minimizer_kwargs) + + else: + self.minimizer_kwargs['options'] = {'ftol': 1e-12} + + if ( + self.minimizer_kwargs['method'].lower() in ('slsqp', 'cobyla', + 'cobyqa', + 'trust-constr') + and ( + minimizer_kwargs is not None and + 'constraints' not in minimizer_kwargs and + constraints is not None + ) or + (self.g_cons is not None) + ): + self.minimizer_kwargs['constraints'] = self.min_cons + + # Process options dict + if options is not None: + self.init_options(options) + else: # Default settings: + self.f_min_true = None + self.minimize_every_iter = True + + # Algorithm limits + self.maxiter = None + self.maxfev = None + self.maxev = None + self.maxtime = None + self.f_min_true = None + self.minhgrd = None + + # Objective function knowledge + self.symmetry = None + + # Algorithm functionality + self.infty_cons_sampl = True + self.local_iter = False + + # Feedback + self.disp = False + + # Remove unknown arguments in self.minimizer_kwargs + # Start with arguments all the solvers have in common + self.min_solver_args = ['fun', 'x0', 'args', + 'callback', 'options', 'method'] + # then add the ones unique to specific solvers + solver_args = { + '_custom': ['jac', 'hess', 'hessp', 'bounds', 'constraints'], + 'nelder-mead': [], + 'powell': [], + 'cg': ['jac'], + 'bfgs': ['jac'], + 'newton-cg': ['jac', 'hess', 'hessp'], + 'l-bfgs-b': ['jac', 'bounds'], + 'tnc': ['jac', 'bounds'], + 'cobyla': ['constraints', 'catol'], + 'cobyqa': ['bounds', 'constraints', 'feasibility_tol'], + 'slsqp': ['jac', 'bounds', 'constraints'], + 'dogleg': ['jac', 'hess'], + 'trust-ncg': ['jac', 'hess', 'hessp'], + 'trust-krylov': ['jac', 'hess', 'hessp'], + 'trust-exact': ['jac', 'hess'], + 'trust-constr': ['jac', 'hess', 'hessp', 'constraints'], + } + method = self.minimizer_kwargs['method'] + self.min_solver_args += solver_args[method.lower()] + + # Only retain the known arguments + def _restrict_to_keys(dictionary, goodkeys): + """Remove keys from dictionary if not in goodkeys - inplace""" + existingkeys = set(dictionary) + for key in existingkeys - set(goodkeys): + dictionary.pop(key, None) + + _restrict_to_keys(self.minimizer_kwargs, self.min_solver_args) + _restrict_to_keys(self.minimizer_kwargs['options'], + self.min_solver_args + ['ftol']) + + # Algorithm controls + # Global controls + self.stop_global = False # Used in the stopping_criteria method + self.break_routine = False # Break the algorithm globally + self.iters = iters # Iterations to be ran + self.iters_done = 0 # Iterations completed + self.n = n # Sampling points per iteration + self.nc = 0 # n # Sampling points to sample in current iteration + self.n_prc = 0 # Processed points (used to track Delaunay iters) + self.n_sampled = 0 # To track no. of sampling points already generated + self.fn = 0 # Number of feasible sampling points evaluations performed + self.hgr = 0 # Homology group rank + # Initially attempt to build the triangulation incrementally: + self.qhull_incremental = True + + # Default settings if no sampling criteria. + if (self.n is None) and (self.iters is None) \ + and (sampling_method == 'simplicial'): + self.n = 2 ** self.dim + 1 + self.nc = 0 # self.n + if self.iters is None: + self.iters = 1 + if (self.n is None) and not (sampling_method == 'simplicial'): + self.n = self.n = 100 + self.nc = 0 # self.n + if (self.n == 100) and (sampling_method == 'simplicial'): + self.n = 2 ** self.dim + 1 + + if not ((self.maxiter is None) and (self.maxfev is None) and ( + self.maxev is None) + and (self.minhgrd is None) and (self.f_min_true is None)): + self.iters = None + + # Set complex construction mode based on a provided stopping criteria: + # Initialise sampling Complex and function cache + # Note that sfield_args=() since args are already wrapped in self.func + # using the_FunctionWrapper class. + self.HC = Complex(dim=self.dim, domain=self.bounds, + sfield=self.func, sfield_args=(), + symmetry=self.symmetry, + constraints=self.constraints, + workers=workers) + + # Choose complex constructor + if sampling_method == 'simplicial': + self.iterate_complex = self.iterate_hypercube + self.sampling_method = sampling_method + + elif sampling_method in ['halton', 'sobol'] or \ + not isinstance(sampling_method, str): + self.iterate_complex = self.iterate_delaunay + # Sampling method used + if sampling_method in ['halton', 'sobol']: + if sampling_method == 'sobol': + self.n = int(2 ** np.ceil(np.log2(self.n))) + # self.n #TODO: Should always be self.n, this is + # unacceptable for shgo, check that nfev behaves as + # expected. + self.nc = 0 + self.sampling_method = 'sobol' + self.qmc_engine = qmc.Sobol(d=self.dim, scramble=False, + seed=0) + else: + self.sampling_method = 'halton' + self.qmc_engine = qmc.Halton(d=self.dim, scramble=True, + seed=0) + + def sampling_method(n, d): + return self.qmc_engine.random(n) + + else: + # A user defined sampling method: + self.sampling_method = 'custom' + + self.sampling = self.sampling_custom + self.sampling_function = sampling_method # F(n, d) + + # Local controls + self.stop_l_iter = False # Local minimisation iterations + self.stop_complex_iter = False # Sampling iterations + + # Initiate storage objects used in algorithm classes + self.minimizer_pool = [] + + # Cache of local minimizers mapped + self.LMC = LMapCache() + + # Initialize return object + self.res = OptimizeResult() # scipy.optimize.OptimizeResult object + self.res.nfev = 0 # Includes each sampling point as func evaluation + self.res.nlfev = 0 # Local function evals for all minimisers + self.res.nljev = 0 # Local Jacobian evals for all minimisers + self.res.nlhev = 0 # Local Hessian evals for all minimisers + + # Initiation aids + def init_options(self, options): + """ + Initiates the options. + + Can also be useful to change parameters after class initiation. + + Parameters + ---------- + options : dict + + Returns + ------- + None + + """ + # Update 'options' dict passed to optimize.minimize + # Do this first so we don't mutate `options` below. + self.minimizer_kwargs['options'].update(options) + + # Ensure that 'jac', 'hess', and 'hessp' are passed directly to + # `minimize` as keywords, not as part of its 'options' dictionary. + for opt in ['jac', 'hess', 'hessp']: + if opt in self.minimizer_kwargs['options']: + self.minimizer_kwargs[opt] = ( + self.minimizer_kwargs['options'].pop(opt)) + + # Default settings: + self.minimize_every_iter = options.get('minimize_every_iter', True) + + # Algorithm limits + # Maximum number of iterations to perform. + self.maxiter = options.get('maxiter', None) + # Maximum number of function evaluations in the feasible domain + self.maxfev = options.get('maxfev', None) + # Maximum number of sampling evaluations (includes searching in + # infeasible points + self.maxev = options.get('maxev', None) + # Maximum processing runtime allowed + self.init = time.time() + self.maxtime = options.get('maxtime', None) + if 'f_min' in options: + # Specify the minimum objective function value, if it is known. + self.f_min_true = options['f_min'] + self.f_tol = options.get('f_tol', 1e-4) + else: + self.f_min_true = None + + self.minhgrd = options.get('minhgrd', None) + + # Objective function knowledge + self.symmetry = options.get('symmetry', False) + if self.symmetry: + self.symmetry = [0, ]*len(self.bounds) + else: + self.symmetry = None + # Algorithm functionality + # Only evaluate a few of the best candidates + self.local_iter = options.get('local_iter', False) + self.infty_cons_sampl = options.get('infty_constraints', True) + + # Feedback + self.disp = options.get('disp', False) + + def __enter__(self): + return self + + def __exit__(self, *args): + return self.HC.V._mapwrapper.__exit__(*args) + + # Iteration properties + # Main construction loop: + def iterate_all(self): + """ + Construct for `iters` iterations. + + If uniform sampling is used, every iteration adds 'n' sampling points. + + Iterations if a stopping criteria (e.g., sampling points or + processing time) has been met. + + """ + if self.disp: + logging.info('Splitting first generation') + + while not self.stop_global: + if self.break_routine: + break + # Iterate complex, process minimisers + self.iterate() + self.stopping_criteria() + + # Build minimiser pool + # Final iteration only needed if pools weren't minimised every + # iteration + if not self.minimize_every_iter: + if not self.break_routine: + self.find_minima() + + self.res.nit = self.iters_done # + 1 + self.fn = self.HC.V.nfev + + def find_minima(self): + """ + Construct the minimizer pool, map the minimizers to local minima + and sort the results into a global return object. + """ + if self.disp: + logging.info('Searching for minimizer pool...') + + self.minimizers() + + if len(self.X_min) != 0: + # Minimize the pool of minimizers with local minimization methods + # Note that if Options['local_iter'] is an `int` instead of default + # value False then only that number of candidates will be minimized + self.minimise_pool(self.local_iter) + # Sort results and build the global return object + self.sort_result() + + # Lowest values used to report in case of failures + self.f_lowest = self.res.fun + self.x_lowest = self.res.x + else: + self.find_lowest_vertex() + + if self.disp: + logging.info(f"Minimiser pool = SHGO.X_min = {self.X_min}") + + def find_lowest_vertex(self): + # Find the lowest objective function value on one of + # the vertices of the simplicial complex + self.f_lowest = np.inf + for x in self.HC.V.cache: + if self.HC.V[x].f < self.f_lowest: + if self.disp: + logging.info(f'self.HC.V[x].f = {self.HC.V[x].f}') + self.f_lowest = self.HC.V[x].f + self.x_lowest = self.HC.V[x].x_a + for lmc in self.LMC.cache: + if self.LMC[lmc].f_min < self.f_lowest: + self.f_lowest = self.LMC[lmc].f_min + self.x_lowest = self.LMC[lmc].x_l + + if self.f_lowest == np.inf: # no feasible point + self.f_lowest = None + self.x_lowest = None + + # Stopping criteria functions: + def finite_iterations(self): + mi = min(x for x in [self.iters, self.maxiter] if x is not None) + if self.disp: + logging.info(f'Iterations done = {self.iters_done} / {mi}') + if self.iters is not None: + if self.iters_done >= (self.iters): + self.stop_global = True + + if self.maxiter is not None: # Stop for infeasible sampling + if self.iters_done >= (self.maxiter): + self.stop_global = True + return self.stop_global + + def finite_fev(self): + # Finite function evals in the feasible domain + if self.disp: + logging.info(f'Function evaluations done = {self.fn} / {self.maxfev}') + if self.fn >= self.maxfev: + self.stop_global = True + return self.stop_global + + def finite_ev(self): + # Finite evaluations including infeasible sampling points + if self.disp: + logging.info(f'Sampling evaluations done = {self.n_sampled} ' + f'/ {self.maxev}') + if self.n_sampled >= self.maxev: + self.stop_global = True + + def finite_time(self): + if self.disp: + logging.info(f'Time elapsed = {time.time() - self.init} ' + f'/ {self.maxtime}') + if (time.time() - self.init) >= self.maxtime: + self.stop_global = True + + def finite_precision(self): + """ + Stop the algorithm if the final function value is known + + Specify in options (with ``self.f_min_true = options['f_min']``) + and the tolerance with ``f_tol = options['f_tol']`` + """ + # If no minimizer has been found use the lowest sampling value + self.find_lowest_vertex() + if self.disp: + logging.info(f'Lowest function evaluation = {self.f_lowest}') + logging.info(f'Specified minimum = {self.f_min_true}') + # If no feasible point was return from test + if self.f_lowest is None: + return self.stop_global + + # Function to stop algorithm at specified percentage error: + if self.f_min_true == 0.0: + if self.f_lowest <= self.f_tol: + self.stop_global = True + else: + pe = (self.f_lowest - self.f_min_true) / abs(self.f_min_true) + if self.f_lowest <= self.f_min_true: + self.stop_global = True + # 2if (pe - self.f_tol) <= abs(1.0 / abs(self.f_min_true)): + if abs(pe) >= 2 * self.f_tol: + warnings.warn( + f"A much lower value than expected f* = {self.f_min_true} " + f"was found f_lowest = {self.f_lowest}", + stacklevel=3 + ) + if pe <= self.f_tol: + self.stop_global = True + + return self.stop_global + + def finite_homology_growth(self): + """ + Stop the algorithm if homology group rank did not grow in iteration. + """ + if self.LMC.size == 0: + return # pass on no reason to stop yet. + self.hgrd = self.LMC.size - self.hgr + + self.hgr = self.LMC.size + if self.hgrd <= self.minhgrd: + self.stop_global = True + if self.disp: + logging.info(f'Current homology growth = {self.hgrd} ' + f' (minimum growth = {self.minhgrd})') + return self.stop_global + + def stopping_criteria(self): + """ + Various stopping criteria ran every iteration + + Returns + ------- + stop : bool + """ + if self.maxiter is not None: + self.finite_iterations() + if self.iters is not None: + self.finite_iterations() + if self.maxfev is not None: + self.finite_fev() + if self.maxev is not None: + self.finite_ev() + if self.maxtime is not None: + self.finite_time() + if self.f_min_true is not None: + self.finite_precision() + if self.minhgrd is not None: + self.finite_homology_growth() + return self.stop_global + + def iterate(self): + self.iterate_complex() + + # Build minimizer pool + if self.minimize_every_iter: + if not self.break_routine: + self.find_minima() # Process minimizer pool + + # Algorithm updates + self.iters_done += 1 + + def iterate_hypercube(self): + """ + Iterate a subdivision of the complex + + Note: called with ``self.iterate_complex()`` after class initiation + """ + # Iterate the complex + if self.disp: + logging.info('Constructing and refining simplicial complex graph ' + 'structure') + if self.n is None: + self.HC.refine_all() + self.n_sampled = self.HC.V.size() # nevs counted + else: + self.HC.refine(self.n) + self.n_sampled += self.n + + if self.disp: + logging.info('Triangulation completed, evaluating all constraints ' + 'and objective function values.') + + # Re-add minimisers to complex + if len(self.LMC.xl_maps) > 0: + for xl in self.LMC.cache: + v = self.HC.V[xl] + v_near = v.star() + for v in v.nn: + v_near = v_near.union(v.nn) + # Reconnect vertices to complex + # if self.HC.connect_vertex_non_symm(tuple(self.LMC[xl].x_l), + # near=v_near): + # continue + # else: + # If failure to find in v_near, then search all vertices + # (very expensive operation: + # self.HC.connect_vertex_non_symm(tuple(self.LMC[xl].x_l) + # ) + + # Evaluate all constraints and functions + self.HC.V.process_pools() + if self.disp: + logging.info('Evaluations completed.') + + # feasible sampling points counted by the triangulation.py routines + self.fn = self.HC.V.nfev + return + + def iterate_delaunay(self): + """ + Build a complex of Delaunay triangulated points + + Note: called with ``self.iterate_complex()`` after class initiation + """ + self.nc += self.n + self.sampled_surface(infty_cons_sampl=self.infty_cons_sampl) + + # Add sampled points to a triangulation, construct self.Tri + if self.disp: + logging.info(f'self.n = {self.n}') + logging.info(f'self.nc = {self.nc}') + logging.info('Constructing and refining simplicial complex graph ' + 'structure from sampling points.') + + if self.dim < 2: + self.Ind_sorted = np.argsort(self.C, axis=0) + self.Ind_sorted = self.Ind_sorted.flatten() + tris = [] + for ind, ind_s in enumerate(self.Ind_sorted): + if ind > 0: + tris.append(self.Ind_sorted[ind - 1:ind + 1]) + + tris = np.array(tris) + # Store 1D triangulation: + self.Tri = namedtuple('Tri', ['points', 'simplices'])(self.C, tris) + self.points = {} + else: + if self.C.shape[0] > self.dim + 1: # Ensure a simplex can be built + self.delaunay_triangulation(n_prc=self.n_prc) + self.n_prc = self.C.shape[0] + + if self.disp: + logging.info('Triangulation completed, evaluating all ' + 'constraints and objective function values.') + + if hasattr(self, 'Tri'): + self.HC.vf_to_vv(self.Tri.points, self.Tri.simplices) + + # Process all pools + # Evaluate all constraints and functions + if self.disp: + logging.info('Triangulation completed, evaluating all constraints ' + 'and objective function values.') + + # Evaluate all constraints and functions + self.HC.V.process_pools() + if self.disp: + logging.info('Evaluations completed.') + + # feasible sampling points counted by the triangulation.py routines + self.fn = self.HC.V.nfev + self.n_sampled = self.nc # nevs counted in triangulation + return + + # Hypercube minimizers + def minimizers(self): + """ + Returns the indexes of all minimizers + """ + self.minimizer_pool = [] + # Note: Can implement parallelization here + for x in self.HC.V.cache: + in_LMC = False + if len(self.LMC.xl_maps) > 0: + for xlmi in self.LMC.xl_maps: + if np.all(np.array(x) == np.array(xlmi)): + in_LMC = True + if in_LMC: + continue + + if self.HC.V[x].minimiser(): + if self.disp: + logging.info('=' * 60) + logging.info(f'v.x = {self.HC.V[x].x_a} is minimizer') + logging.info(f'v.f = {self.HC.V[x].f} is minimizer') + logging.info('=' * 30) + + if self.HC.V[x] not in self.minimizer_pool: + self.minimizer_pool.append(self.HC.V[x]) + + if self.disp: + logging.info('Neighbors:') + logging.info('=' * 30) + for vn in self.HC.V[x].nn: + logging.info(f'x = {vn.x} || f = {vn.f}') + + logging.info('=' * 60) + self.minimizer_pool_F = [] + self.X_min = [] + # normalized tuple in the Vertex cache + self.X_min_cache = {} # Cache used in hypercube sampling + + for v in self.minimizer_pool: + self.X_min.append(v.x_a) + self.minimizer_pool_F.append(v.f) + self.X_min_cache[tuple(v.x_a)] = v.x + + self.minimizer_pool_F = np.array(self.minimizer_pool_F) + self.X_min = np.array(self.X_min) + + # TODO: Only do this if global mode + self.sort_min_pool() + + return self.X_min + + # Local minimisation + # Minimiser pool processing + def minimise_pool(self, force_iter=False): + """ + This processing method can optionally minimise only the best candidate + solutions in the minimiser pool + + Parameters + ---------- + force_iter : int + Number of starting minimizers to process (can be specified + globally or locally) + + """ + # Find first local minimum + # NOTE: Since we always minimize this value regardless it is a waste to + # build the topograph first before minimizing + lres_f_min = self.minimize(self.X_min[0], ind=self.minimizer_pool[0]) + + # Trim minimized point from current minimizer set + self.trim_min_pool(0) + + while not self.stop_l_iter: + # Global stopping criteria: + self.stopping_criteria() + + # Note first iteration is outside loop: + if force_iter: + force_iter -= 1 + if force_iter == 0: + self.stop_l_iter = True + break + + if np.shape(self.X_min)[0] == 0: + self.stop_l_iter = True + break + + # Construct topograph from current minimizer set + # (NOTE: This is a very small topograph using only the minizer pool + # , it might be worth using some graph theory tools instead. + self.g_topograph(lres_f_min.x, self.X_min) + + # Find local minimum at the miniser with the greatest Euclidean + # distance from the current solution + ind_xmin_l = self.Z[:, -1] + lres_f_min = self.minimize(self.Ss[-1, :], self.minimizer_pool[-1]) + + # Trim minimised point from current minimizer set + self.trim_min_pool(ind_xmin_l) + + # Reset controls + self.stop_l_iter = False + return + + def sort_min_pool(self): + # Sort to find minimum func value in min_pool + self.ind_f_min = np.argsort(self.minimizer_pool_F) + self.minimizer_pool = np.array(self.minimizer_pool)[self.ind_f_min] + self.minimizer_pool_F = np.array(self.minimizer_pool_F)[ + self.ind_f_min] + return + + def trim_min_pool(self, trim_ind): + self.X_min = np.delete(self.X_min, trim_ind, axis=0) + self.minimizer_pool_F = np.delete(self.minimizer_pool_F, trim_ind) + self.minimizer_pool = np.delete(self.minimizer_pool, trim_ind) + return + + def g_topograph(self, x_min, X_min): + """ + Returns the topographical vector stemming from the specified value + ``x_min`` for the current feasible set ``X_min`` with True boolean + values indicating positive entries and False values indicating + negative entries. + + """ + x_min = np.array([x_min]) + self.Y = spatial.distance.cdist(x_min, X_min, 'euclidean') + # Find sorted indexes of spatial distances: + self.Z = np.argsort(self.Y, axis=-1) + + self.Ss = X_min[self.Z][0] + self.minimizer_pool = self.minimizer_pool[self.Z] + self.minimizer_pool = self.minimizer_pool[0] + return self.Ss + + # Local bound functions + def construct_lcb_simplicial(self, v_min): + """ + Construct locally (approximately) convex bounds + + Parameters + ---------- + v_min : Vertex object + The minimizer vertex + + Returns + ------- + cbounds : list of lists + List of size dimension with length-2 list of bounds for each + dimension. + + """ + cbounds = [[x_b_i[0], x_b_i[1]] for x_b_i in self.bounds] + # Loop over all bounds + for vn in v_min.nn: + for i, x_i in enumerate(vn.x_a): + # Lower bound + if (x_i < v_min.x_a[i]) and (x_i > cbounds[i][0]): + cbounds[i][0] = x_i + + # Upper bound + if (x_i > v_min.x_a[i]) and (x_i < cbounds[i][1]): + cbounds[i][1] = x_i + + if self.disp: + logging.info(f'cbounds found for v_min.x_a = {v_min.x_a}') + logging.info(f'cbounds = {cbounds}') + + return cbounds + + def construct_lcb_delaunay(self, v_min, ind=None): + """ + Construct locally (approximately) convex bounds + + Parameters + ---------- + v_min : Vertex object + The minimizer vertex + + Returns + ------- + cbounds : list of lists + List of size dimension with length-2 list of bounds for each + dimension. + """ + cbounds = [[x_b_i[0], x_b_i[1]] for x_b_i in self.bounds] + + return cbounds + + # Minimize a starting point locally + def minimize(self, x_min, ind=None): + """ + This function is used to calculate the local minima using the specified + sampling point as a starting value. + + Parameters + ---------- + x_min : vector of floats + Current starting point to minimize. + + Returns + ------- + lres : OptimizeResult + The local optimization result represented as a `OptimizeResult` + object. + """ + # Use minima maps if vertex was already run + if self.disp: + logging.info(f'Vertex minimiser maps = {self.LMC.v_maps}') + + if self.LMC[x_min].lres is not None: + logging.info(f'Found self.LMC[x_min].lres = ' + f'{self.LMC[x_min].lres}') + return self.LMC[x_min].lres + + if self.callback is not None: + logging.info(f'Callback for minimizer starting at {x_min}:') + + if self.disp: + logging.info(f'Starting minimization at {x_min}...') + + if self.sampling_method == 'simplicial': + x_min_t = tuple(x_min) + # Find the normalized tuple in the Vertex cache: + x_min_t_norm = self.X_min_cache[tuple(x_min_t)] + x_min_t_norm = tuple(x_min_t_norm) + g_bounds = self.construct_lcb_simplicial(self.HC.V[x_min_t_norm]) + if 'bounds' in self.min_solver_args: + self.minimizer_kwargs['bounds'] = g_bounds + logging.info(self.minimizer_kwargs['bounds']) + + else: + g_bounds = self.construct_lcb_delaunay(x_min, ind=ind) + if 'bounds' in self.min_solver_args: + self.minimizer_kwargs['bounds'] = g_bounds + logging.info(self.minimizer_kwargs['bounds']) + + if self.disp and 'bounds' in self.minimizer_kwargs: + logging.info('bounds in kwarg:') + logging.info(self.minimizer_kwargs['bounds']) + + # Local minimization using scipy.optimize.minimize: + lres = minimize(self.func, x_min, **self.minimizer_kwargs) + + if self.disp: + logging.info(f'lres = {lres}') + + # Local function evals for all minimizers + self.res.nlfev += lres.nfev + if 'njev' in lres: + self.res.nljev += lres.njev + if 'nhev' in lres: + self.res.nlhev += lres.nhev + + try: # Needed because of the brain dead 1x1 NumPy arrays + lres.fun = lres.fun[0] + except (IndexError, TypeError): + lres.fun + + # Append minima maps + self.LMC[x_min] + self.LMC.add_res(x_min, lres, bounds=g_bounds) + + return lres + + # Post local minimization processing + def sort_result(self): + """ + Sort results and build the global return object + """ + # Sort results in local minima cache + results = self.LMC.sort_cache_result() + self.res.xl = results['xl'] + self.res.funl = results['funl'] + self.res.x = results['x'] + self.res.fun = results['fun'] + + # Add local func evals to sampling func evals + # Count the number of feasible vertices and add to local func evals: + self.res.nfev = self.fn + self.res.nlfev + return self.res + + # Algorithm controls + def fail_routine(self, mes=("Failed to converge")): + self.break_routine = True + self.res.success = False + self.X_min = [None] + self.res.message = mes + + def sampled_surface(self, infty_cons_sampl=False): + """ + Sample the function surface. + + There are 2 modes, if ``infty_cons_sampl`` is True then the sampled + points that are generated outside the feasible domain will be + assigned an ``inf`` value in accordance with SHGO rules. + This guarantees convergence and usually requires less objective + function evaluations at the computational costs of more Delaunay + triangulation points. + + If ``infty_cons_sampl`` is False, then the infeasible points are + discarded and only a subspace of the sampled points are used. This + comes at the cost of the loss of guaranteed convergence and usually + requires more objective function evaluations. + """ + # Generate sampling points + if self.disp: + logging.info('Generating sampling points') + self.sampling(self.nc, self.dim) + if len(self.LMC.xl_maps) > 0: + self.C = np.vstack((self.C, np.array(self.LMC.xl_maps))) + if not infty_cons_sampl: + # Find subspace of feasible points + if self.g_cons is not None: + self.sampling_subspace() + + # Sort remaining samples + self.sorted_samples() + + # Find objective function references + self.n_sampled = self.nc + + def sampling_custom(self, n, dim): + """ + Generates uniform sampling points in a hypercube and scales the points + to the bound limits. + """ + # Generate sampling points. + # Generate uniform sample points in [0, 1]^m \subset R^m + if self.n_sampled == 0: + self.C = self.sampling_function(n, dim) + else: + self.C = self.sampling_function(n, dim) + # Distribute over bounds + for i in range(len(self.bounds)): + self.C[:, i] = (self.C[:, i] * + (self.bounds[i][1] - self.bounds[i][0]) + + self.bounds[i][0]) + return self.C + + def sampling_subspace(self): + """Find subspace of feasible points from g_func definition""" + # Subspace of feasible points. + for ind, g in enumerate(self.g_cons): + # C.shape = (Z, dim) where Z is the number of sampling points to + # evaluate and dim is the dimensionality of the problem. + # the constraint function may not be vectorised so have to step + # through each sampling point sequentially. + feasible = np.array( + [np.all(g(x_C, *self.g_args[ind]) >= 0.0) for x_C in self.C], + dtype=bool + ) + self.C = self.C[feasible] + + if self.C.size == 0: + self.res.message = ('No sampling point found within the ' + + 'feasible set. Increasing sampling ' + + 'size.') + # sampling correctly for both 1-D and >1-D cases + if self.disp: + logging.info(self.res.message) + + def sorted_samples(self): # Validated + """Find indexes of the sorted sampling points""" + self.Ind_sorted = np.argsort(self.C, axis=0) + self.Xs = self.C[self.Ind_sorted] + return self.Ind_sorted, self.Xs + + def delaunay_triangulation(self, n_prc=0): + if hasattr(self, 'Tri') and self.qhull_incremental: + # TODO: Uncertain if n_prc needs to add len(self.LMC.xl_maps) + # in self.sampled_surface + self.Tri.add_points(self.C[n_prc:, :]) + else: + try: + self.Tri = spatial.Delaunay(self.C, + incremental=self.qhull_incremental, + ) + except spatial.QhullError: + if str(sys.exc_info()[1])[:6] == 'QH6239': + logging.warning('QH6239 Qhull precision error detected, ' + 'this usually occurs when no bounds are ' + 'specified, Qhull can only run with ' + 'handling cocircular/cospherical points' + ' and in this case incremental mode is ' + 'switched off. The performance of shgo ' + 'will be reduced in this mode.') + self.qhull_incremental = False + self.Tri = spatial.Delaunay(self.C, + incremental= + self.qhull_incremental) + else: + raise + + return self.Tri + + +class LMap: + def __init__(self, v): + self.v = v + self.x_l = None + self.lres = None + self.f_min = None + self.lbounds = [] + + +class LMapCache: + def __init__(self): + self.cache = {} + + # Lists for search queries + self.v_maps = [] + self.xl_maps = [] + self.xl_maps_set = set() + self.f_maps = [] + self.lbound_maps = [] + self.size = 0 + + def __getitem__(self, v): + try: + v = np.ndarray.tolist(v) + except TypeError: + pass + v = tuple(v) + try: + return self.cache[v] + except KeyError: + xval = LMap(v) + self.cache[v] = xval + + return self.cache[v] + + def add_res(self, v, lres, bounds=None): + v = np.ndarray.tolist(v) + v = tuple(v) + self.cache[v].x_l = lres.x + self.cache[v].lres = lres + self.cache[v].f_min = lres.fun + self.cache[v].lbounds = bounds + + # Update cache size + self.size += 1 + + # Cache lists for search queries + self.v_maps.append(v) + self.xl_maps.append(lres.x) + self.xl_maps_set.add(tuple(lres.x)) + self.f_maps.append(lres.fun) + self.lbound_maps.append(bounds) + + def sort_cache_result(self): + """ + Sort results and build the global return object + """ + results = {} + # Sort results and save + self.xl_maps = np.array(self.xl_maps) + self.f_maps = np.array(self.f_maps) + + # Sorted indexes in Func_min + ind_sorted = np.argsort(self.f_maps) + + # Save ordered list of minima + results['xl'] = self.xl_maps[ind_sorted] # Ordered x vals + self.f_maps = np.array(self.f_maps) + results['funl'] = self.f_maps[ind_sorted] + results['funl'] = results['funl'].T + + # Find global of all minimizers + results['x'] = self.xl_maps[ind_sorted[0]] # Save global minima + results['fun'] = self.f_maps[ind_sorted[0]] # Save global fun value + + self.xl_maps = np.ndarray.tolist(self.xl_maps) + self.f_maps = np.ndarray.tolist(self.f_maps) + return results diff --git a/llava_next/lib/python3.10/site-packages/scipy/optimize/_slsqp_py.py b/llava_next/lib/python3.10/site-packages/scipy/optimize/_slsqp_py.py new file mode 100644 index 0000000000000000000000000000000000000000..b6b78aafdd2c13ac58b392e8c520f6caaa730d3f --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/scipy/optimize/_slsqp_py.py @@ -0,0 +1,510 @@ +""" +This module implements the Sequential Least Squares Programming optimization +algorithm (SLSQP), originally developed by Dieter Kraft. +See http://www.netlib.org/toms/733 + +Functions +--------- +.. autosummary:: + :toctree: generated/ + + approx_jacobian + fmin_slsqp + +""" + +__all__ = ['approx_jacobian', 'fmin_slsqp'] + +import numpy as np +from scipy.optimize._slsqp import slsqp +from numpy import (zeros, array, linalg, append, concatenate, finfo, + sqrt, vstack, isfinite, atleast_1d) +from ._optimize import (OptimizeResult, _check_unknown_options, + _prepare_scalar_function, _clip_x_for_func, + _check_clip_x) +from ._numdiff import approx_derivative +from ._constraints import old_bound_to_new, _arr_to_scalar +from scipy._lib._array_api import atleast_nd, array_namespace + + +__docformat__ = "restructuredtext en" + +_epsilon = sqrt(finfo(float).eps) + + +def approx_jacobian(x, func, epsilon, *args): + """ + Approximate the Jacobian matrix of a callable function. + + Parameters + ---------- + x : array_like + The state vector at which to compute the Jacobian matrix. + func : callable f(x,*args) + The vector-valued function. + epsilon : float + The perturbation used to determine the partial derivatives. + args : sequence + Additional arguments passed to func. + + Returns + ------- + An array of dimensions ``(lenf, lenx)`` where ``lenf`` is the length + of the outputs of `func`, and ``lenx`` is the number of elements in + `x`. + + Notes + ----- + The approximation is done using forward differences. + + """ + # approx_derivative returns (m, n) == (lenf, lenx) + jac = approx_derivative(func, x, method='2-point', abs_step=epsilon, + args=args) + # if func returns a scalar jac.shape will be (lenx,). Make sure + # it's at least a 2D array. + return np.atleast_2d(jac) + + +def fmin_slsqp(func, x0, eqcons=(), f_eqcons=None, ieqcons=(), f_ieqcons=None, + bounds=(), fprime=None, fprime_eqcons=None, + fprime_ieqcons=None, args=(), iter=100, acc=1.0E-6, + iprint=1, disp=None, full_output=0, epsilon=_epsilon, + callback=None): + """ + Minimize a function using Sequential Least Squares Programming + + Python interface function for the SLSQP Optimization subroutine + originally implemented by Dieter Kraft. + + Parameters + ---------- + func : callable f(x,*args) + Objective function. Must return a scalar. + x0 : 1-D ndarray of float + Initial guess for the independent variable(s). + eqcons : list, optional + A list of functions of length n such that + eqcons[j](x,*args) == 0.0 in a successfully optimized + problem. + f_eqcons : callable f(x,*args), optional + Returns a 1-D array in which each element must equal 0.0 in a + successfully optimized problem. If f_eqcons is specified, + eqcons is ignored. + ieqcons : list, optional + A list of functions of length n such that + ieqcons[j](x,*args) >= 0.0 in a successfully optimized + problem. + f_ieqcons : callable f(x,*args), optional + Returns a 1-D ndarray in which each element must be greater or + equal to 0.0 in a successfully optimized problem. If + f_ieqcons is specified, ieqcons is ignored. + bounds : list, optional + A list of tuples specifying the lower and upper bound + for each independent variable [(xl0, xu0),(xl1, xu1),...] + Infinite values will be interpreted as large floating values. + fprime : callable `f(x,*args)`, optional + A function that evaluates the partial derivatives of func. + fprime_eqcons : callable `f(x,*args)`, optional + A function of the form `f(x, *args)` that returns the m by n + array of equality constraint normals. If not provided, + the normals will be approximated. The array returned by + fprime_eqcons should be sized as ( len(eqcons), len(x0) ). + fprime_ieqcons : callable `f(x,*args)`, optional + A function of the form `f(x, *args)` that returns the m by n + array of inequality constraint normals. If not provided, + the normals will be approximated. The array returned by + fprime_ieqcons should be sized as ( len(ieqcons), len(x0) ). + args : sequence, optional + Additional arguments passed to func and fprime. + iter : int, optional + The maximum number of iterations. + acc : float, optional + Requested accuracy. + iprint : int, optional + The verbosity of fmin_slsqp : + + * iprint <= 0 : Silent operation + * iprint == 1 : Print summary upon completion (default) + * iprint >= 2 : Print status of each iterate and summary + disp : int, optional + Overrides the iprint interface (preferred). + full_output : bool, optional + If False, return only the minimizer of func (default). + Otherwise, output final objective function and summary + information. + epsilon : float, optional + The step size for finite-difference derivative estimates. + callback : callable, optional + Called after each iteration, as ``callback(x)``, where ``x`` is the + current parameter vector. + + Returns + ------- + out : ndarray of float + The final minimizer of func. + fx : ndarray of float, if full_output is true + The final value of the objective function. + its : int, if full_output is true + The number of iterations. + imode : int, if full_output is true + The exit mode from the optimizer (see below). + smode : string, if full_output is true + Message describing the exit mode from the optimizer. + + See also + -------- + minimize: Interface to minimization algorithms for multivariate + functions. See the 'SLSQP' `method` in particular. + + Notes + ----- + Exit modes are defined as follows :: + + -1 : Gradient evaluation required (g & a) + 0 : Optimization terminated successfully + 1 : Function evaluation required (f & c) + 2 : More equality constraints than independent variables + 3 : More than 3*n iterations in LSQ subproblem + 4 : Inequality constraints incompatible + 5 : Singular matrix E in LSQ subproblem + 6 : Singular matrix C in LSQ subproblem + 7 : Rank-deficient equality constraint subproblem HFTI + 8 : Positive directional derivative for linesearch + 9 : Iteration limit reached + + Examples + -------- + Examples are given :ref:`in the tutorial `. + + """ + if disp is not None: + iprint = disp + + opts = {'maxiter': iter, + 'ftol': acc, + 'iprint': iprint, + 'disp': iprint != 0, + 'eps': epsilon, + 'callback': callback} + + # Build the constraints as a tuple of dictionaries + cons = () + # 1. constraints of the 1st kind (eqcons, ieqcons); no Jacobian; take + # the same extra arguments as the objective function. + cons += tuple({'type': 'eq', 'fun': c, 'args': args} for c in eqcons) + cons += tuple({'type': 'ineq', 'fun': c, 'args': args} for c in ieqcons) + # 2. constraints of the 2nd kind (f_eqcons, f_ieqcons) and their Jacobian + # (fprime_eqcons, fprime_ieqcons); also take the same extra arguments + # as the objective function. + if f_eqcons: + cons += ({'type': 'eq', 'fun': f_eqcons, 'jac': fprime_eqcons, + 'args': args}, ) + if f_ieqcons: + cons += ({'type': 'ineq', 'fun': f_ieqcons, 'jac': fprime_ieqcons, + 'args': args}, ) + + res = _minimize_slsqp(func, x0, args, jac=fprime, bounds=bounds, + constraints=cons, **opts) + if full_output: + return res['x'], res['fun'], res['nit'], res['status'], res['message'] + else: + return res['x'] + + +def _minimize_slsqp(func, x0, args=(), jac=None, bounds=None, + constraints=(), + maxiter=100, ftol=1.0E-6, iprint=1, disp=False, + eps=_epsilon, callback=None, finite_diff_rel_step=None, + **unknown_options): + """ + Minimize a scalar function of one or more variables using Sequential + Least Squares Programming (SLSQP). + + Options + ------- + ftol : float + Precision goal for the value of f in the stopping criterion. + eps : float + Step size used for numerical approximation of the Jacobian. + disp : bool + Set to True to print convergence messages. If False, + `verbosity` is ignored and set to 0. + maxiter : int + Maximum number of iterations. + finite_diff_rel_step : None or array_like, optional + If `jac in ['2-point', '3-point', 'cs']` the relative step size to + use for numerical approximation of `jac`. The absolute step + size is computed as ``h = rel_step * sign(x) * max(1, abs(x))``, + possibly adjusted to fit into the bounds. For ``method='3-point'`` + the sign of `h` is ignored. If None (default) then step is selected + automatically. + """ + _check_unknown_options(unknown_options) + iter = maxiter - 1 + acc = ftol + epsilon = eps + + if not disp: + iprint = 0 + + # Transform x0 into an array. + xp = array_namespace(x0) + x0 = atleast_nd(x0, ndim=1, xp=xp) + dtype = xp.float64 + if xp.isdtype(x0.dtype, "real floating"): + dtype = x0.dtype + x = xp.reshape(xp.astype(x0, dtype), -1) + + # SLSQP is sent 'old-style' bounds, 'new-style' bounds are required by + # ScalarFunction + if bounds is None or len(bounds) == 0: + new_bounds = (-np.inf, np.inf) + else: + new_bounds = old_bound_to_new(bounds) + + # clip the initial guess to bounds, otherwise ScalarFunction doesn't work + x = np.clip(x, new_bounds[0], new_bounds[1]) + + # Constraints are triaged per type into a dictionary of tuples + if isinstance(constraints, dict): + constraints = (constraints, ) + + cons = {'eq': (), 'ineq': ()} + for ic, con in enumerate(constraints): + # check type + try: + ctype = con['type'].lower() + except KeyError as e: + raise KeyError('Constraint %d has no type defined.' % ic) from e + except TypeError as e: + raise TypeError('Constraints must be defined using a ' + 'dictionary.') from e + except AttributeError as e: + raise TypeError("Constraint's type must be a string.") from e + else: + if ctype not in ['eq', 'ineq']: + raise ValueError("Unknown constraint type '%s'." % con['type']) + + # check function + if 'fun' not in con: + raise ValueError('Constraint %d has no function defined.' % ic) + + # check Jacobian + cjac = con.get('jac') + if cjac is None: + # approximate Jacobian function. The factory function is needed + # to keep a reference to `fun`, see gh-4240. + def cjac_factory(fun): + def cjac(x, *args): + x = _check_clip_x(x, new_bounds) + + if jac in ['2-point', '3-point', 'cs']: + return approx_derivative(fun, x, method=jac, args=args, + rel_step=finite_diff_rel_step, + bounds=new_bounds) + else: + return approx_derivative(fun, x, method='2-point', + abs_step=epsilon, args=args, + bounds=new_bounds) + + return cjac + cjac = cjac_factory(con['fun']) + + # update constraints' dictionary + cons[ctype] += ({'fun': con['fun'], + 'jac': cjac, + 'args': con.get('args', ())}, ) + + exit_modes = {-1: "Gradient evaluation required (g & a)", + 0: "Optimization terminated successfully", + 1: "Function evaluation required (f & c)", + 2: "More equality constraints than independent variables", + 3: "More than 3*n iterations in LSQ subproblem", + 4: "Inequality constraints incompatible", + 5: "Singular matrix E in LSQ subproblem", + 6: "Singular matrix C in LSQ subproblem", + 7: "Rank-deficient equality constraint subproblem HFTI", + 8: "Positive directional derivative for linesearch", + 9: "Iteration limit reached"} + + # Set the parameters that SLSQP will need + # meq, mieq: number of equality and inequality constraints + meq = sum(map(len, [atleast_1d(c['fun'](x, *c['args'])) + for c in cons['eq']])) + mieq = sum(map(len, [atleast_1d(c['fun'](x, *c['args'])) + for c in cons['ineq']])) + # m = The total number of constraints + m = meq + mieq + # la = The number of constraints, or 1 if there are no constraints + la = array([1, m]).max() + # n = The number of independent variables + n = len(x) + + # Define the workspaces for SLSQP + n1 = n + 1 + mineq = m - meq + n1 + n1 + len_w = (3*n1+m)*(n1+1)+(n1-meq+1)*(mineq+2) + 2*mineq+(n1+mineq)*(n1-meq) \ + + 2*meq + n1 + ((n+1)*n)//2 + 2*m + 3*n + 3*n1 + 1 + len_jw = mineq + w = zeros(len_w) + jw = zeros(len_jw) + + # Decompose bounds into xl and xu + if bounds is None or len(bounds) == 0: + xl = np.empty(n, dtype=float) + xu = np.empty(n, dtype=float) + xl.fill(np.nan) + xu.fill(np.nan) + else: + bnds = array([(_arr_to_scalar(l), _arr_to_scalar(u)) + for (l, u) in bounds], float) + if bnds.shape[0] != n: + raise IndexError('SLSQP Error: the length of bounds is not ' + 'compatible with that of x0.') + + with np.errstate(invalid='ignore'): + bnderr = bnds[:, 0] > bnds[:, 1] + + if bnderr.any(): + raise ValueError('SLSQP Error: lb > ub in bounds %s.' % + ', '.join(str(b) for b in bnderr)) + xl, xu = bnds[:, 0], bnds[:, 1] + + # Mark infinite bounds with nans; the Fortran code understands this + infbnd = ~isfinite(bnds) + xl[infbnd[:, 0]] = np.nan + xu[infbnd[:, 1]] = np.nan + + # ScalarFunction provides function and gradient evaluation + sf = _prepare_scalar_function(func, x, jac=jac, args=args, epsilon=eps, + finite_diff_rel_step=finite_diff_rel_step, + bounds=new_bounds) + # gh11403 SLSQP sometimes exceeds bounds by 1 or 2 ULP, make sure this + # doesn't get sent to the func/grad evaluator. + wrapped_fun = _clip_x_for_func(sf.fun, new_bounds) + wrapped_grad = _clip_x_for_func(sf.grad, new_bounds) + + # Initialize the iteration counter and the mode value + mode = array(0, int) + acc = array(acc, float) + majiter = array(iter, int) + majiter_prev = 0 + + # Initialize internal SLSQP state variables + alpha = array(0, float) + f0 = array(0, float) + gs = array(0, float) + h1 = array(0, float) + h2 = array(0, float) + h3 = array(0, float) + h4 = array(0, float) + t = array(0, float) + t0 = array(0, float) + tol = array(0, float) + iexact = array(0, int) + incons = array(0, int) + ireset = array(0, int) + itermx = array(0, int) + line = array(0, int) + n1 = array(0, int) + n2 = array(0, int) + n3 = array(0, int) + + # Print the header if iprint >= 2 + if iprint >= 2: + print("%5s %5s %16s %16s" % ("NIT", "FC", "OBJFUN", "GNORM")) + + # mode is zero on entry, so call objective, constraints and gradients + # there should be no func evaluations here because it's cached from + # ScalarFunction + fx = wrapped_fun(x) + g = append(wrapped_grad(x), 0.0) + c = _eval_constraint(x, cons) + a = _eval_con_normals(x, cons, la, n, m, meq, mieq) + + while 1: + # Call SLSQP + slsqp(m, meq, x, xl, xu, fx, c, g, a, acc, majiter, mode, w, jw, + alpha, f0, gs, h1, h2, h3, h4, t, t0, tol, + iexact, incons, ireset, itermx, line, + n1, n2, n3) + + if mode == 1: # objective and constraint evaluation required + fx = wrapped_fun(x) + c = _eval_constraint(x, cons) + + if mode == -1: # gradient evaluation required + g = append(wrapped_grad(x), 0.0) + a = _eval_con_normals(x, cons, la, n, m, meq, mieq) + + if majiter > majiter_prev: + # call callback if major iteration has incremented + if callback is not None: + callback(np.copy(x)) + + # Print the status of the current iterate if iprint > 2 + if iprint >= 2: + print("%5i %5i % 16.6E % 16.6E" % (majiter, sf.nfev, + fx, linalg.norm(g))) + + # If exit mode is not -1 or 1, slsqp has completed + if abs(mode) != 1: + break + + majiter_prev = int(majiter) + + # Optimization loop complete. Print status if requested + if iprint >= 1: + print(exit_modes[int(mode)] + " (Exit mode " + str(mode) + ')') + print(" Current function value:", fx) + print(" Iterations:", majiter) + print(" Function evaluations:", sf.nfev) + print(" Gradient evaluations:", sf.ngev) + + return OptimizeResult(x=x, fun=fx, jac=g[:-1], nit=int(majiter), + nfev=sf.nfev, njev=sf.ngev, status=int(mode), + message=exit_modes[int(mode)], success=(mode == 0)) + + +def _eval_constraint(x, cons): + # Compute constraints + if cons['eq']: + c_eq = concatenate([atleast_1d(con['fun'](x, *con['args'])) + for con in cons['eq']]) + else: + c_eq = zeros(0) + + if cons['ineq']: + c_ieq = concatenate([atleast_1d(con['fun'](x, *con['args'])) + for con in cons['ineq']]) + else: + c_ieq = zeros(0) + + # Now combine c_eq and c_ieq into a single matrix + c = concatenate((c_eq, c_ieq)) + return c + + +def _eval_con_normals(x, cons, la, n, m, meq, mieq): + # Compute the normals of the constraints + if cons['eq']: + a_eq = vstack([con['jac'](x, *con['args']) + for con in cons['eq']]) + else: # no equality constraint + a_eq = zeros((meq, n)) + + if cons['ineq']: + a_ieq = vstack([con['jac'](x, *con['args']) + for con in cons['ineq']]) + else: # no inequality constraint + a_ieq = zeros((mieq, n)) + + # Now combine a_eq and a_ieq into a single a matrix + if m == 0: # no constraints + a = zeros((la, n)) + else: + a = vstack((a_eq, a_ieq)) + a = concatenate((a, zeros([la, 1])), 1) + + return a diff --git a/llava_next/lib/python3.10/site-packages/scipy/optimize/_trustregion.py b/llava_next/lib/python3.10/site-packages/scipy/optimize/_trustregion.py new file mode 100644 index 0000000000000000000000000000000000000000..f2355cf68ac8e1cac7e2688a9b91364ff2b2dcee --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/scipy/optimize/_trustregion.py @@ -0,0 +1,304 @@ +"""Trust-region optimization.""" +import math +import warnings + +import numpy as np +import scipy.linalg +from ._optimize import (_check_unknown_options, _status_message, + OptimizeResult, _prepare_scalar_function, + _call_callback_maybe_halt) +from scipy.optimize._hessian_update_strategy import HessianUpdateStrategy +from scipy.optimize._differentiable_functions import FD_METHODS +__all__ = [] + + +def _wrap_function(function, args): + # wraps a minimizer function to count number of evaluations + # and to easily provide an args kwd. + ncalls = [0] + if function is None: + return ncalls, None + + def function_wrapper(x, *wrapper_args): + ncalls[0] += 1 + # A copy of x is sent to the user function (gh13740) + return function(np.copy(x), *(wrapper_args + args)) + + return ncalls, function_wrapper + + +class BaseQuadraticSubproblem: + """ + Base/abstract class defining the quadratic model for trust-region + minimization. Child classes must implement the ``solve`` method. + + Values of the objective function, Jacobian and Hessian (if provided) at + the current iterate ``x`` are evaluated on demand and then stored as + attributes ``fun``, ``jac``, ``hess``. + """ + + def __init__(self, x, fun, jac, hess=None, hessp=None): + self._x = x + self._f = None + self._g = None + self._h = None + self._g_mag = None + self._cauchy_point = None + self._newton_point = None + self._fun = fun + self._jac = jac + self._hess = hess + self._hessp = hessp + + def __call__(self, p): + return self.fun + np.dot(self.jac, p) + 0.5 * np.dot(p, self.hessp(p)) + + @property + def fun(self): + """Value of objective function at current iteration.""" + if self._f is None: + self._f = self._fun(self._x) + return self._f + + @property + def jac(self): + """Value of Jacobian of objective function at current iteration.""" + if self._g is None: + self._g = self._jac(self._x) + return self._g + + @property + def hess(self): + """Value of Hessian of objective function at current iteration.""" + if self._h is None: + self._h = self._hess(self._x) + return self._h + + def hessp(self, p): + if self._hessp is not None: + return self._hessp(self._x, p) + else: + return np.dot(self.hess, p) + + @property + def jac_mag(self): + """Magnitude of jacobian of objective function at current iteration.""" + if self._g_mag is None: + self._g_mag = scipy.linalg.norm(self.jac) + return self._g_mag + + def get_boundaries_intersections(self, z, d, trust_radius): + """ + Solve the scalar quadratic equation ``||z + t d|| == trust_radius``. + This is like a line-sphere intersection. + Return the two values of t, sorted from low to high. + """ + a = np.dot(d, d) + b = 2 * np.dot(z, d) + c = np.dot(z, z) - trust_radius**2 + sqrt_discriminant = math.sqrt(b*b - 4*a*c) + + # The following calculation is mathematically + # equivalent to: + # ta = (-b - sqrt_discriminant) / (2*a) + # tb = (-b + sqrt_discriminant) / (2*a) + # but produce smaller round off errors. + # Look at Matrix Computation p.97 + # for a better justification. + aux = b + math.copysign(sqrt_discriminant, b) + ta = -aux / (2*a) + tb = -2*c / aux + return sorted([ta, tb]) + + def solve(self, trust_radius): + raise NotImplementedError('The solve method should be implemented by ' + 'the child class') + + +def _minimize_trust_region(fun, x0, args=(), jac=None, hess=None, hessp=None, + subproblem=None, initial_trust_radius=1.0, + max_trust_radius=1000.0, eta=0.15, gtol=1e-4, + maxiter=None, disp=False, return_all=False, + callback=None, inexact=True, **unknown_options): + """ + Minimization of scalar function of one or more variables using a + trust-region algorithm. + + Options for the trust-region algorithm are: + initial_trust_radius : float + Initial trust radius. + max_trust_radius : float + Never propose steps that are longer than this value. + eta : float + Trust region related acceptance stringency for proposed steps. + gtol : float + Gradient norm must be less than `gtol` + before successful termination. + maxiter : int + Maximum number of iterations to perform. + disp : bool + If True, print convergence message. + inexact : bool + Accuracy to solve subproblems. If True requires less nonlinear + iterations, but more vector products. Only effective for method + trust-krylov. + + This function is called by the `minimize` function. + It is not supposed to be called directly. + """ + _check_unknown_options(unknown_options) + + if jac is None: + raise ValueError('Jacobian is currently required for trust-region ' + 'methods') + if hess is None and hessp is None: + raise ValueError('Either the Hessian or the Hessian-vector product ' + 'is currently required for trust-region methods') + if subproblem is None: + raise ValueError('A subproblem solving strategy is required for ' + 'trust-region methods') + if not (0 <= eta < 0.25): + raise Exception('invalid acceptance stringency') + if max_trust_radius <= 0: + raise Exception('the max trust radius must be positive') + if initial_trust_radius <= 0: + raise ValueError('the initial trust radius must be positive') + if initial_trust_radius >= max_trust_radius: + raise ValueError('the initial trust radius must be less than the ' + 'max trust radius') + + # force the initial guess into a nice format + x0 = np.asarray(x0).flatten() + + # A ScalarFunction representing the problem. This caches calls to fun, jac, + # hess. + sf = _prepare_scalar_function(fun, x0, jac=jac, hess=hess, args=args) + fun = sf.fun + jac = sf.grad + if callable(hess): + hess = sf.hess + elif callable(hessp): + # this elif statement must come before examining whether hess + # is estimated by FD methods or a HessianUpdateStrategy + pass + elif (hess in FD_METHODS or isinstance(hess, HessianUpdateStrategy)): + # If the Hessian is being estimated by finite differences or a + # Hessian update strategy then ScalarFunction.hess returns a + # LinearOperator or a HessianUpdateStrategy. This enables the + # calculation/creation of a hessp. BUT you only want to do this + # if the user *hasn't* provided a callable(hessp) function. + hess = None + + def hessp(x, p, *args): + return sf.hess(x).dot(p) + else: + raise ValueError('Either the Hessian or the Hessian-vector product ' + 'is currently required for trust-region methods') + + # ScalarFunction doesn't represent hessp + nhessp, hessp = _wrap_function(hessp, args) + + # limit the number of iterations + if maxiter is None: + maxiter = len(x0)*200 + + # init the search status + warnflag = 0 + + # initialize the search + trust_radius = initial_trust_radius + x = x0 + if return_all: + allvecs = [x] + m = subproblem(x, fun, jac, hess, hessp) + k = 0 + + # search for the function min + # do not even start if the gradient is small enough + while m.jac_mag >= gtol: + + # Solve the sub-problem. + # This gives us the proposed step relative to the current position + # and it tells us whether the proposed step + # has reached the trust region boundary or not. + try: + p, hits_boundary = m.solve(trust_radius) + except np.linalg.LinAlgError: + warnflag = 3 + break + + # calculate the predicted value at the proposed point + predicted_value = m(p) + + # define the local approximation at the proposed point + x_proposed = x + p + m_proposed = subproblem(x_proposed, fun, jac, hess, hessp) + + # evaluate the ratio defined in equation (4.4) + actual_reduction = m.fun - m_proposed.fun + predicted_reduction = m.fun - predicted_value + if predicted_reduction <= 0: + warnflag = 2 + break + rho = actual_reduction / predicted_reduction + + # update the trust radius according to the actual/predicted ratio + if rho < 0.25: + trust_radius *= 0.25 + elif rho > 0.75 and hits_boundary: + trust_radius = min(2*trust_radius, max_trust_radius) + + # if the ratio is high enough then accept the proposed step + if rho > eta: + x = x_proposed + m = m_proposed + + # append the best guess, call back, increment the iteration count + if return_all: + allvecs.append(np.copy(x)) + k += 1 + + intermediate_result = OptimizeResult(x=x, fun=m.fun) + if _call_callback_maybe_halt(callback, intermediate_result): + break + + # check if the gradient is small enough to stop + if m.jac_mag < gtol: + warnflag = 0 + break + + # check if we have looked at enough iterations + if k >= maxiter: + warnflag = 1 + break + + # print some stuff if requested + status_messages = ( + _status_message['success'], + _status_message['maxiter'], + 'A bad approximation caused failure to predict improvement.', + 'A linalg error occurred, such as a non-psd Hessian.', + ) + if disp: + if warnflag == 0: + print(status_messages[warnflag]) + else: + warnings.warn(status_messages[warnflag], RuntimeWarning, stacklevel=3) + print(" Current function value: %f" % m.fun) + print(" Iterations: %d" % k) + print(" Function evaluations: %d" % sf.nfev) + print(" Gradient evaluations: %d" % sf.ngev) + print(" Hessian evaluations: %d" % (sf.nhev + nhessp[0])) + + result = OptimizeResult(x=x, success=(warnflag == 0), status=warnflag, + fun=m.fun, jac=m.jac, nfev=sf.nfev, njev=sf.ngev, + nhev=sf.nhev + nhessp[0], nit=k, + message=status_messages[warnflag]) + + if hess is not None: + result['hess'] = m.hess + + if return_all: + result['allvecs'] = allvecs + + return result diff --git a/llava_next/lib/python3.10/site-packages/scipy/optimize/_trustregion_dogleg.py b/llava_next/lib/python3.10/site-packages/scipy/optimize/_trustregion_dogleg.py new file mode 100644 index 0000000000000000000000000000000000000000..a54abd60c703408d6c87cb5020d6781fdf0213c7 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/scipy/optimize/_trustregion_dogleg.py @@ -0,0 +1,122 @@ +"""Dog-leg trust-region optimization.""" +import numpy as np +import scipy.linalg +from ._trustregion import (_minimize_trust_region, BaseQuadraticSubproblem) + +__all__ = [] + + +def _minimize_dogleg(fun, x0, args=(), jac=None, hess=None, + **trust_region_options): + """ + Minimization of scalar function of one or more variables using + the dog-leg trust-region algorithm. + + Options + ------- + initial_trust_radius : float + Initial trust-region radius. + max_trust_radius : float + Maximum value of the trust-region radius. No steps that are longer + than this value will be proposed. + eta : float + Trust region related acceptance stringency for proposed steps. + gtol : float + Gradient norm must be less than `gtol` before successful + termination. + + """ + if jac is None: + raise ValueError('Jacobian is required for dogleg minimization') + if not callable(hess): + raise ValueError('Hessian is required for dogleg minimization') + return _minimize_trust_region(fun, x0, args=args, jac=jac, hess=hess, + subproblem=DoglegSubproblem, + **trust_region_options) + + +class DoglegSubproblem(BaseQuadraticSubproblem): + """Quadratic subproblem solved by the dogleg method""" + + def cauchy_point(self): + """ + The Cauchy point is minimal along the direction of steepest descent. + """ + if self._cauchy_point is None: + g = self.jac + Bg = self.hessp(g) + self._cauchy_point = -(np.dot(g, g) / np.dot(g, Bg)) * g + return self._cauchy_point + + def newton_point(self): + """ + The Newton point is a global minimum of the approximate function. + """ + if self._newton_point is None: + g = self.jac + B = self.hess + cho_info = scipy.linalg.cho_factor(B) + self._newton_point = -scipy.linalg.cho_solve(cho_info, g) + return self._newton_point + + def solve(self, trust_radius): + """ + Minimize a function using the dog-leg trust-region algorithm. + + This algorithm requires function values and first and second derivatives. + It also performs a costly Hessian decomposition for most iterations, + and the Hessian is required to be positive definite. + + Parameters + ---------- + trust_radius : float + We are allowed to wander only this far away from the origin. + + Returns + ------- + p : ndarray + The proposed step. + hits_boundary : bool + True if the proposed step is on the boundary of the trust region. + + Notes + ----- + The Hessian is required to be positive definite. + + References + ---------- + .. [1] Jorge Nocedal and Stephen Wright, + Numerical Optimization, second edition, + Springer-Verlag, 2006, page 73. + """ + + # Compute the Newton point. + # This is the optimum for the quadratic model function. + # If it is inside the trust radius then return this point. + p_best = self.newton_point() + if scipy.linalg.norm(p_best) < trust_radius: + hits_boundary = False + return p_best, hits_boundary + + # Compute the Cauchy point. + # This is the predicted optimum along the direction of steepest descent. + p_u = self.cauchy_point() + + # If the Cauchy point is outside the trust region, + # then return the point where the path intersects the boundary. + p_u_norm = scipy.linalg.norm(p_u) + if p_u_norm >= trust_radius: + p_boundary = p_u * (trust_radius / p_u_norm) + hits_boundary = True + return p_boundary, hits_boundary + + # Compute the intersection of the trust region boundary + # and the line segment connecting the Cauchy and Newton points. + # This requires solving a quadratic equation. + # ||p_u + t*(p_best - p_u)||**2 == trust_radius**2 + # Solve this for positive time t using the quadratic formula. + _, tb = self.get_boundaries_intersections(p_u, p_best - p_u, + trust_radius) + p_boundary = p_u + tb * (p_best - p_u) + hits_boundary = True + return p_boundary, hits_boundary diff --git a/llava_next/lib/python3.10/site-packages/scipy/optimize/_trustregion_exact.py b/llava_next/lib/python3.10/site-packages/scipy/optimize/_trustregion_exact.py new file mode 100644 index 0000000000000000000000000000000000000000..21fc3d5609d2b41eb5b5ad840ef464522565054c --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/scipy/optimize/_trustregion_exact.py @@ -0,0 +1,438 @@ +"""Nearly exact trust-region optimization subproblem.""" +import numpy as np +from scipy.linalg import (norm, get_lapack_funcs, solve_triangular, + cho_solve) +from ._trustregion import (_minimize_trust_region, BaseQuadraticSubproblem) + +__all__ = ['_minimize_trustregion_exact', + 'estimate_smallest_singular_value', + 'singular_leading_submatrix', + 'IterativeSubproblem'] + + +def _minimize_trustregion_exact(fun, x0, args=(), jac=None, hess=None, + **trust_region_options): + """ + Minimization of scalar function of one or more variables using + a nearly exact trust-region algorithm. + + Options + ------- + initial_trust_radius : float + Initial trust-region radius. + max_trust_radius : float + Maximum value of the trust-region radius. No steps that are longer + than this value will be proposed. + eta : float + Trust region related acceptance stringency for proposed steps. + gtol : float + Gradient norm must be less than ``gtol`` before successful + termination. + """ + + if jac is None: + raise ValueError('Jacobian is required for trust region ' + 'exact minimization.') + if not callable(hess): + raise ValueError('Hessian matrix is required for trust region ' + 'exact minimization.') + return _minimize_trust_region(fun, x0, args=args, jac=jac, hess=hess, + subproblem=IterativeSubproblem, + **trust_region_options) + + +def estimate_smallest_singular_value(U): + """Given upper triangular matrix ``U`` estimate the smallest singular + value and the correspondent right singular vector in O(n**2) operations. + + Parameters + ---------- + U : ndarray + Square upper triangular matrix. + + Returns + ------- + s_min : float + Estimated smallest singular value of the provided matrix. + z_min : ndarray + Estimatied right singular vector. + + Notes + ----- + The procedure is based on [1]_ and is done in two steps. First, it finds + a vector ``e`` with components selected from {+1, -1} such that the + solution ``w`` from the system ``U.T w = e`` is as large as possible. + Next it estimate ``U v = w``. The smallest singular value is close + to ``norm(w)/norm(v)`` and the right singular vector is close + to ``v/norm(v)``. + + The estimation will be better more ill-conditioned is the matrix. + + References + ---------- + .. [1] Cline, A. K., Moler, C. B., Stewart, G. W., Wilkinson, J. H. + An estimate for the condition number of a matrix. 1979. + SIAM Journal on Numerical Analysis, 16(2), 368-375. + """ + + U = np.atleast_2d(U) + m, n = U.shape + + if m != n: + raise ValueError("A square triangular matrix should be provided.") + + # A vector `e` with components selected from {+1, -1} + # is selected so that the solution `w` to the system + # `U.T w = e` is as large as possible. Implementation + # based on algorithm 3.5.1, p. 142, from reference [2] + # adapted for lower triangular matrix. + + p = np.zeros(n) + w = np.empty(n) + + # Implemented according to: Golub, G. H., Van Loan, C. F. (2013). + # "Matrix computations". Forth Edition. JHU press. pp. 140-142. + for k in range(n): + wp = (1-p[k]) / U.T[k, k] + wm = (-1-p[k]) / U.T[k, k] + pp = p[k+1:] + U.T[k+1:, k]*wp + pm = p[k+1:] + U.T[k+1:, k]*wm + + if abs(wp) + norm(pp, 1) >= abs(wm) + norm(pm, 1): + w[k] = wp + p[k+1:] = pp + else: + w[k] = wm + p[k+1:] = pm + + # The system `U v = w` is solved using backward substitution. + v = solve_triangular(U, w) + + v_norm = norm(v) + w_norm = norm(w) + + # Smallest singular value + s_min = w_norm / v_norm + + # Associated vector + z_min = v / v_norm + + return s_min, z_min + + +def gershgorin_bounds(H): + """ + Given a square matrix ``H`` compute upper + and lower bounds for its eigenvalues (Gregoshgorin Bounds). + Defined ref. [1]. + + References + ---------- + .. [1] Conn, A. R., Gould, N. I., & Toint, P. L. + Trust region methods. 2000. Siam. pp. 19. + """ + + H_diag = np.diag(H) + H_diag_abs = np.abs(H_diag) + H_row_sums = np.sum(np.abs(H), axis=1) + lb = np.min(H_diag + H_diag_abs - H_row_sums) + ub = np.max(H_diag - H_diag_abs + H_row_sums) + + return lb, ub + + +def singular_leading_submatrix(A, U, k): + """ + Compute term that makes the leading ``k`` by ``k`` + submatrix from ``A`` singular. + + Parameters + ---------- + A : ndarray + Symmetric matrix that is not positive definite. + U : ndarray + Upper triangular matrix resulting of an incomplete + Cholesky decomposition of matrix ``A``. + k : int + Positive integer such that the leading k by k submatrix from + `A` is the first non-positive definite leading submatrix. + + Returns + ------- + delta : float + Amount that should be added to the element (k, k) of the + leading k by k submatrix of ``A`` to make it singular. + v : ndarray + A vector such that ``v.T B v = 0``. Where B is the matrix A after + ``delta`` is added to its element (k, k). + """ + + # Compute delta + delta = np.sum(U[:k-1, k-1]**2) - A[k-1, k-1] + + n = len(A) + + # Inicialize v + v = np.zeros(n) + v[k-1] = 1 + + # Compute the remaining values of v by solving a triangular system. + if k != 1: + v[:k-1] = solve_triangular(U[:k-1, :k-1], -U[:k-1, k-1]) + + return delta, v + + +class IterativeSubproblem(BaseQuadraticSubproblem): + """Quadratic subproblem solved by nearly exact iterative method. + + Notes + ----- + This subproblem solver was based on [1]_, [2]_ and [3]_, + which implement similar algorithms. The algorithm is basically + that of [1]_ but ideas from [2]_ and [3]_ were also used. + + References + ---------- + .. [1] A.R. Conn, N.I. Gould, and P.L. Toint, "Trust region methods", + Siam, pp. 169-200, 2000. + .. [2] J. Nocedal and S. Wright, "Numerical optimization", + Springer Science & Business Media. pp. 83-91, 2006. + .. [3] J.J. More and D.C. Sorensen, "Computing a trust region step", + SIAM Journal on Scientific and Statistical Computing, vol. 4(3), + pp. 553-572, 1983. + """ + + # UPDATE_COEFF appears in reference [1]_ + # in formula 7.3.14 (p. 190) named as "theta". + # As recommended there it value is fixed in 0.01. + UPDATE_COEFF = 0.01 + + EPS = np.finfo(float).eps + + def __init__(self, x, fun, jac, hess, hessp=None, + k_easy=0.1, k_hard=0.2): + + super().__init__(x, fun, jac, hess) + + # When the trust-region shrinks in two consecutive + # calculations (``tr_radius < previous_tr_radius``) + # the lower bound ``lambda_lb`` may be reused, + # facilitating the convergence. To indicate no + # previous value is known at first ``previous_tr_radius`` + # is set to -1 and ``lambda_lb`` to None. + self.previous_tr_radius = -1 + self.lambda_lb = None + + self.niter = 0 + + # ``k_easy`` and ``k_hard`` are parameters used + # to determine the stop criteria to the iterative + # subproblem solver. Take a look at pp. 194-197 + # from reference _[1] for a more detailed description. + self.k_easy = k_easy + self.k_hard = k_hard + + # Get Lapack function for cholesky decomposition. + # The implemented SciPy wrapper does not return + # the incomplete factorization needed by the method. + self.cholesky, = get_lapack_funcs(('potrf',), (self.hess,)) + + # Get info about Hessian + self.dimension = len(self.hess) + self.hess_gershgorin_lb,\ + self.hess_gershgorin_ub = gershgorin_bounds(self.hess) + self.hess_inf = norm(self.hess, np.inf) + self.hess_fro = norm(self.hess, 'fro') + + # A constant such that for vectors smaller than that + # backward substituition is not reliable. It was stabilished + # based on Golub, G. H., Van Loan, C. F. (2013). + # "Matrix computations". Forth Edition. JHU press., p.165. + self.CLOSE_TO_ZERO = self.dimension * self.EPS * self.hess_inf + + def _initial_values(self, tr_radius): + """Given a trust radius, return a good initial guess for + the damping factor, the lower bound and the upper bound. + The values were chosen accordingly to the guidelines on + section 7.3.8 (p. 192) from [1]_. + """ + + # Upper bound for the damping factor + lambda_ub = max(0, self.jac_mag/tr_radius + min(-self.hess_gershgorin_lb, + self.hess_fro, + self.hess_inf)) + + # Lower bound for the damping factor + lambda_lb = max(0, -min(self.hess.diagonal()), + self.jac_mag/tr_radius - min(self.hess_gershgorin_ub, + self.hess_fro, + self.hess_inf)) + + # Improve bounds with previous info + if tr_radius < self.previous_tr_radius: + lambda_lb = max(self.lambda_lb, lambda_lb) + + # Initial guess for the damping factor + if lambda_lb == 0: + lambda_initial = 0 + else: + lambda_initial = max(np.sqrt(lambda_lb * lambda_ub), + lambda_lb + self.UPDATE_COEFF*(lambda_ub-lambda_lb)) + + return lambda_initial, lambda_lb, lambda_ub + + def solve(self, tr_radius): + """Solve quadratic subproblem""" + + lambda_current, lambda_lb, lambda_ub = self._initial_values(tr_radius) + n = self.dimension + hits_boundary = True + already_factorized = False + self.niter = 0 + + while True: + + # Compute Cholesky factorization + if already_factorized: + already_factorized = False + else: + H = self.hess+lambda_current*np.eye(n) + U, info = self.cholesky(H, lower=False, + overwrite_a=False, + clean=True) + + self.niter += 1 + + # Check if factorization succeeded + if info == 0 and self.jac_mag > self.CLOSE_TO_ZERO: + # Successful factorization + + # Solve `U.T U p = s` + p = cho_solve((U, False), -self.jac) + + p_norm = norm(p) + + # Check for interior convergence + if p_norm <= tr_radius and lambda_current == 0: + hits_boundary = False + break + + # Solve `U.T w = p` + w = solve_triangular(U, p, trans='T') + + w_norm = norm(w) + + # Compute Newton step accordingly to + # formula (4.44) p.87 from ref [2]_. + delta_lambda = (p_norm/w_norm)**2 * (p_norm-tr_radius)/tr_radius + lambda_new = lambda_current + delta_lambda + + if p_norm < tr_radius: # Inside boundary + s_min, z_min = estimate_smallest_singular_value(U) + + ta, tb = self.get_boundaries_intersections(p, z_min, + tr_radius) + + # Choose `step_len` with the smallest magnitude. + # The reason for this choice is explained at + # ref [3]_, p. 6 (Immediately before the formula + # for `tau`). + step_len = min([ta, tb], key=abs) + + # Compute the quadratic term (p.T*H*p) + quadratic_term = np.dot(p, np.dot(H, p)) + + # Check stop criteria + relative_error = ((step_len**2 * s_min**2) + / (quadratic_term + lambda_current*tr_radius**2)) + if relative_error <= self.k_hard: + p += step_len * z_min + break + + # Update uncertanty bounds + lambda_ub = lambda_current + lambda_lb = max(lambda_lb, lambda_current - s_min**2) + + # Compute Cholesky factorization + H = self.hess + lambda_new*np.eye(n) + c, info = self.cholesky(H, lower=False, + overwrite_a=False, + clean=True) + + # Check if the factorization have succeeded + # + if info == 0: # Successful factorization + # Update damping factor + lambda_current = lambda_new + already_factorized = True + else: # Unsuccessful factorization + # Update uncertanty bounds + lambda_lb = max(lambda_lb, lambda_new) + + # Update damping factor + lambda_current = max( + np.sqrt(lambda_lb * lambda_ub), + lambda_lb + self.UPDATE_COEFF*(lambda_ub-lambda_lb) + ) + + else: # Outside boundary + # Check stop criteria + relative_error = abs(p_norm - tr_radius) / tr_radius + if relative_error <= self.k_easy: + break + + # Update uncertanty bounds + lambda_lb = lambda_current + + # Update damping factor + lambda_current = lambda_new + + elif info == 0 and self.jac_mag <= self.CLOSE_TO_ZERO: + # jac_mag very close to zero + + # Check for interior convergence + if lambda_current == 0: + p = np.zeros(n) + hits_boundary = False + break + + s_min, z_min = estimate_smallest_singular_value(U) + step_len = tr_radius + + # Check stop criteria + if (step_len**2 * s_min**2 + <= self.k_hard * lambda_current * tr_radius**2): + p = step_len * z_min + break + + # Update uncertanty bounds + lambda_ub = lambda_current + lambda_lb = max(lambda_lb, lambda_current - s_min**2) + + # Update damping factor + lambda_current = max( + np.sqrt(lambda_lb * lambda_ub), + lambda_lb + self.UPDATE_COEFF*(lambda_ub-lambda_lb) + ) + + else: # Unsuccessful factorization + + # Compute auxiliary terms + delta, v = singular_leading_submatrix(H, U, info) + v_norm = norm(v) + + # Update uncertanty interval + lambda_lb = max(lambda_lb, lambda_current + delta/v_norm**2) + + # Update damping factor + lambda_current = max( + np.sqrt(lambda_lb * lambda_ub), + lambda_lb + self.UPDATE_COEFF*(lambda_ub-lambda_lb) + ) + + self.lambda_lb = lambda_lb + self.lambda_current = lambda_current + self.previous_tr_radius = tr_radius + + return p, hits_boundary diff --git a/llava_next/lib/python3.10/site-packages/scipy/optimize/_trustregion_krylov.py b/llava_next/lib/python3.10/site-packages/scipy/optimize/_trustregion_krylov.py new file mode 100644 index 0000000000000000000000000000000000000000..54e861ae2de02164966a33c437e5fdb08ba3006c --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/scipy/optimize/_trustregion_krylov.py @@ -0,0 +1,65 @@ +from ._trustregion import (_minimize_trust_region) +from ._trlib import (get_trlib_quadratic_subproblem) + +__all__ = ['_minimize_trust_krylov'] + +def _minimize_trust_krylov(fun, x0, args=(), jac=None, hess=None, hessp=None, + inexact=True, **trust_region_options): + """ + Minimization of a scalar function of one or more variables using + a nearly exact trust-region algorithm that only requires matrix + vector products with the hessian matrix. + + .. versionadded:: 1.0.0 + + Options + ------- + inexact : bool, optional + Accuracy to solve subproblems. If True requires less nonlinear + iterations, but more vector products. + """ + + if jac is None: + raise ValueError('Jacobian is required for trust region ', + 'exact minimization.') + if hess is None and hessp is None: + raise ValueError('Either the Hessian or the Hessian-vector product ' + 'is required for Krylov trust-region minimization') + + # tol_rel specifies the termination tolerance relative to the initial + # gradient norm in the Krylov subspace iteration. + + # - tol_rel_i specifies the tolerance for interior convergence. + # - tol_rel_b specifies the tolerance for boundary convergence. + # in nonlinear programming applications it is not necessary to solve + # the boundary case as exact as the interior case. + + # - setting tol_rel_i=-2 leads to a forcing sequence in the Krylov + # subspace iteration leading to quadratic convergence if eventually + # the trust region stays inactive. + # - setting tol_rel_b=-3 leads to a forcing sequence in the Krylov + # subspace iteration leading to superlinear convergence as long + # as the iterates hit the trust region boundary. + + # For details consult the documentation of trlib_krylov_min + # in _trlib/trlib_krylov.h + # + # Optimality of this choice of parameters among a range of possibilities + # has been tested on the unconstrained subset of the CUTEst library. + + if inexact: + return _minimize_trust_region(fun, x0, args=args, jac=jac, + hess=hess, hessp=hessp, + subproblem=get_trlib_quadratic_subproblem( + tol_rel_i=-2.0, tol_rel_b=-3.0, + disp=trust_region_options.get('disp', False) + ), + **trust_region_options) + else: + return _minimize_trust_region(fun, x0, args=args, jac=jac, + hess=hess, hessp=hessp, + subproblem=get_trlib_quadratic_subproblem( + tol_rel_i=1e-8, tol_rel_b=1e-6, + disp=trust_region_options.get('disp', False) + ), + **trust_region_options) diff --git a/llava_next/lib/python3.10/site-packages/scipy/optimize/_zeros.cpython-310-x86_64-linux-gnu.so b/llava_next/lib/python3.10/site-packages/scipy/optimize/_zeros.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..7af3971d3d8f44903d9da2be40e4e414cbf6463d Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/scipy/optimize/_zeros.cpython-310-x86_64-linux-gnu.so differ diff --git a/llava_next/lib/python3.10/site-packages/scipy/optimize/cython_optimize.pxd b/llava_next/lib/python3.10/site-packages/scipy/optimize/cython_optimize.pxd new file mode 100644 index 0000000000000000000000000000000000000000..d35f8da68b34d3a587f3a99326770d8550a2135c --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/scipy/optimize/cython_optimize.pxd @@ -0,0 +1,11 @@ +# Public Cython API declarations +# +# See doc/source/dev/contributor/public_cython_api.rst for guidelines + + +# The following cimport statement provides legacy ABI +# support. Changing it causes an ABI forward-compatibility break +# (gh-11793), so we currently leave it as is (no further cimport +# statements should be used in this file). +from scipy.optimize.cython_optimize._zeros cimport ( + brentq, brenth, ridder, bisect, zeros_full_output) diff --git a/llava_next/lib/python3.10/site-packages/scipy/optimize/linesearch.py b/llava_next/lib/python3.10/site-packages/scipy/optimize/linesearch.py new file mode 100644 index 0000000000000000000000000000000000000000..cb34b25092da34991c868683da3d6a894d1a7f80 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/scipy/optimize/linesearch.py @@ -0,0 +1,18 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.optimize` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + + +__all__ = ["line_search"] # noqa: F822 + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="optimize", module="linesearch", + private_modules=["_linesearch"], all=__all__, + attribute=name) diff --git a/llava_next/lib/python3.10/site-packages/scipy/optimize/minpack.py b/llava_next/lib/python3.10/site-packages/scipy/optimize/minpack.py new file mode 100644 index 0000000000000000000000000000000000000000..29fddef537361d8508e6343d23b2c3c7d6d12ec6 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/scipy/optimize/minpack.py @@ -0,0 +1,27 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.optimize` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + + +__all__ = [ # noqa: F822 + 'OptimizeResult', + 'OptimizeWarning', + 'curve_fit', + 'fixed_point', + 'fsolve', + 'least_squares', + 'leastsq', + 'zeros', +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="optimize", module="minpack", + private_modules=["_minpack_py"], all=__all__, + attribute=name) diff --git a/llava_next/lib/python3.10/site-packages/scipy/optimize/moduleTNC.py b/llava_next/lib/python3.10/site-packages/scipy/optimize/moduleTNC.py new file mode 100644 index 0000000000000000000000000000000000000000..3fc5884ed5c39437b7681395419d641443a1fdb8 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/scipy/optimize/moduleTNC.py @@ -0,0 +1,19 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.optimize` namespace for importing the functions +# included below. + + +from scipy._lib.deprecation import _sub_module_deprecation + + +__all__ = [] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="optimize", module="moduleTNC", + private_modules=["_moduleTNC"], all=__all__, + attribute=name) diff --git a/llava_next/lib/python3.10/site-packages/scipy/optimize/nonlin.py b/llava_next/lib/python3.10/site-packages/scipy/optimize/nonlin.py new file mode 100644 index 0000000000000000000000000000000000000000..20b490b40ef790a2943d539790b45fc378df2c76 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/scipy/optimize/nonlin.py @@ -0,0 +1,29 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.optimize` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + + +__all__ = [ # noqa: F822 + 'BroydenFirst', + 'InverseJacobian', + 'KrylovJacobian', + 'anderson', + 'broyden1', + 'broyden2', + 'diagbroyden', + 'excitingmixing', + 'linearmixing', + 'newton_krylov', +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="optimize", module="nonlin", + private_modules=["_nonlin"], all=__all__, + attribute=name) diff --git a/llava_next/lib/python3.10/site-packages/scipy/optimize/optimize.py b/llava_next/lib/python3.10/site-packages/scipy/optimize/optimize.py new file mode 100644 index 0000000000000000000000000000000000000000..4db770e5f6e921906c916f2650003d92f5507791 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/scipy/optimize/optimize.py @@ -0,0 +1,40 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.optimize` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + + +__all__ = [ # noqa: F822 + 'OptimizeResult', + 'OptimizeWarning', + 'approx_fprime', + 'bracket', + 'brent', + 'brute', + 'check_grad', + 'fmin', + 'fmin_bfgs', + 'fmin_cg', + 'fmin_ncg', + 'fmin_powell', + 'fminbound', + 'golden', + 'line_search', + 'rosen', + 'rosen_der', + 'rosen_hess', + 'rosen_hess_prod', + 'show_options', + 'zeros', +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="optimize", module="optimize", + private_modules=["_optimize"], all=__all__, + attribute=name) diff --git a/llava_next/lib/python3.10/site-packages/scipy/optimize/tnc.py b/llava_next/lib/python3.10/site-packages/scipy/optimize/tnc.py new file mode 100644 index 0000000000000000000000000000000000000000..e0f66058bbcc501eb1303eb3075cb55705b93192 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/scipy/optimize/tnc.py @@ -0,0 +1,22 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.optimize` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + + +__all__ = [ # noqa: F822 + 'OptimizeResult', + 'fmin_tnc', + 'zeros', +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="optimize", module="tnc", + private_modules=["_tnc"], all=__all__, + attribute=name) diff --git a/llava_next/lib/python3.10/site-packages/scipy/optimize/zeros.py b/llava_next/lib/python3.10/site-packages/scipy/optimize/zeros.py new file mode 100644 index 0000000000000000000000000000000000000000..907d49d37fc1e7476e81a25dbbc0d3910cbbe004 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/scipy/optimize/zeros.py @@ -0,0 +1,26 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.optimize` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + + +__all__ = [ # noqa: F822 + 'RootResults', + 'bisect', + 'brenth', + 'brentq', + 'newton', + 'ridder', + 'toms748', +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="optimize", module="zeros", + private_modules=["_zeros_py"], all=__all__, + attribute=name) diff --git a/llava_next/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/__init__.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a752d0b89ca0f62f7ee823b4628f94dc1e205f0e Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/__init__.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/cosine_cdf.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/cosine_cdf.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..119950bb27be0e58b84b630a58a615360f43651c Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/cosine_cdf.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/expn_asy.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/expn_asy.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6775c2d7d8514c8a054c3a3e965aa87a2ca75c7d Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/expn_asy.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/gammainc_asy.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/gammainc_asy.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..035ea858123cd88da1322f9fa28957d54afdaf57 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/gammainc_asy.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/gammainc_data.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/gammainc_data.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..881ba23fd9f5c4fca8c235e68b6d2267c823a3bd Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/gammainc_data.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/hyp2f1_data.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/hyp2f1_data.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..38792b5a8d708385cb8bb8791712558daa6615f3 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/hyp2f1_data.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/lambertw.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/lambertw.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a6891c0e5cb3883c039dd8458489096aebafa252 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/lambertw.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/loggamma.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/loggamma.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dd8c5cd7c807a307abba9e156670810e055a8549 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/loggamma.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/struve_convergence.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/struve_convergence.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..98866c4126826d4d9dc2187ba7cb06309df52c9b Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/struve_convergence.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/utils.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a5f755b8e68c6ae5773c96c570909d52b4867a66 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/utils.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/wright_bessel.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/wright_bessel.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..097b85bdd0b3e48286c0319532f20d861b98ed73 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/wright_bessel.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/wright_bessel_data.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/wright_bessel_data.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fb0e6e65c093ab52f38e4b7c2d3a9a399b661372 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/wright_bessel_data.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/wrightomega.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/wrightomega.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..de957653311bb9141098b8186261c068430ba64c Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/wrightomega.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/zetac.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/zetac.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..daf57eba2152aefed046e644ab05ff51c757d241 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/zetac.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/scipy/special/_precompute/cosine_cdf.py b/llava_next/lib/python3.10/site-packages/scipy/special/_precompute/cosine_cdf.py new file mode 100644 index 0000000000000000000000000000000000000000..662c12bc74b31478c87471fbd1cce8bea285e765 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/scipy/special/_precompute/cosine_cdf.py @@ -0,0 +1,17 @@ +import mpmath + + +def f(x): + return (mpmath.pi + x + mpmath.sin(x)) / (2*mpmath.pi) + + +# Note: 40 digits might be overkill; a few more digits than the default +# might be sufficient. +mpmath.mp.dps = 40 +ts = mpmath.taylor(f, -mpmath.pi, 20) +p, q = mpmath.pade(ts, 9, 10) + +p = [float(c) for c in p] +q = [float(c) for c in q] +print('p =', p) +print('q =', q) diff --git a/llava_next/lib/python3.10/site-packages/scipy/special/_precompute/expn_asy.py b/llava_next/lib/python3.10/site-packages/scipy/special/_precompute/expn_asy.py new file mode 100644 index 0000000000000000000000000000000000000000..3491b8acd588a2cacfc48f0a3a60c6ae88c3e8c5 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/scipy/special/_precompute/expn_asy.py @@ -0,0 +1,54 @@ +"""Precompute the polynomials for the asymptotic expansion of the +generalized exponential integral. + +Sources +------- +[1] NIST, Digital Library of Mathematical Functions, + https://dlmf.nist.gov/8.20#ii + +""" +import os + +try: + import sympy + from sympy import Poly + x = sympy.symbols('x') +except ImportError: + pass + + +def generate_A(K): + A = [Poly(1, x)] + for k in range(K): + A.append(Poly(1 - 2*k*x, x)*A[k] + Poly(x*(x + 1))*A[k].diff()) + return A + + +WARNING = """\ +/* This file was automatically generated by _precompute/expn_asy.py. + * Do not edit it manually! + */ +""" + + +def main(): + print(__doc__) + fn = os.path.join('..', 'cephes', 'expn.h') + + K = 12 + A = generate_A(K) + with open(fn + '.new', 'w') as f: + f.write(WARNING) + f.write(f"#define nA {len(A)}\n") + for k, Ak in enumerate(A): + ', '.join([str(x.evalf(18)) for x in Ak.coeffs()]) + f.write(f"static const double A{k}[] = {{tmp}};\n") + ", ".join([f"A{k}" for k in range(K + 1)]) + f.write("static const double *A[] = {{tmp}};\n") + ", ".join([str(Ak.degree()) for Ak in A]) + f.write("static const int Adegs[] = {{tmp}};\n") + os.rename(fn + '.new', fn) + + +if __name__ == "__main__": + main() diff --git a/llava_next/lib/python3.10/site-packages/scipy/special/_precompute/gammainc_data.py b/llava_next/lib/python3.10/site-packages/scipy/special/_precompute/gammainc_data.py new file mode 100644 index 0000000000000000000000000000000000000000..ce8ae5f51b77f37367dc26cf08f3a0e64e3429a4 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/scipy/special/_precompute/gammainc_data.py @@ -0,0 +1,124 @@ +"""Compute gammainc and gammaincc for large arguments and parameters +and save the values to data files for use in tests. We can't just +compare to mpmath's gammainc in test_mpmath.TestSystematic because it +would take too long. + +Note that mpmath's gammainc is computed using hypercomb, but since it +doesn't allow the user to increase the maximum number of terms used in +the series it doesn't converge for many arguments. To get around this +we copy the mpmath implementation but use more terms. + +This takes about 17 minutes to run on a 2.3 GHz Macbook Pro with 4GB +ram. + +Sources: +[1] Fredrik Johansson and others. mpmath: a Python library for + arbitrary-precision floating-point arithmetic (version 0.19), + December 2013. http://mpmath.org/. + +""" +import os +from time import time +import numpy as np +from numpy import pi + +from scipy.special._mptestutils import mpf2float + +try: + import mpmath as mp +except ImportError: + pass + + +def gammainc(a, x, dps=50, maxterms=10**8): + """Compute gammainc exactly like mpmath does but allow for more + summands in hypercomb. See + + mpmath/functions/expintegrals.py#L134 + + in the mpmath github repository. + + """ + with mp.workdps(dps): + z, a, b = mp.mpf(a), mp.mpf(x), mp.mpf(x) + G = [z] + negb = mp.fneg(b, exact=True) + + def h(z): + T1 = [mp.exp(negb), b, z], [1, z, -1], [], G, [1], [1+z], b + return (T1,) + + res = mp.hypercomb(h, [z], maxterms=maxterms) + return mpf2float(res) + + +def gammaincc(a, x, dps=50, maxterms=10**8): + """Compute gammaincc exactly like mpmath does but allow for more + terms in hypercomb. See + + mpmath/functions/expintegrals.py#L187 + + in the mpmath github repository. + + """ + with mp.workdps(dps): + z, a = a, x + + if mp.isint(z): + try: + # mpmath has a fast integer path + return mpf2float(mp.gammainc(z, a=a, regularized=True)) + except mp.libmp.NoConvergence: + pass + nega = mp.fneg(a, exact=True) + G = [z] + # Use 2F0 series when possible; fall back to lower gamma representation + try: + def h(z): + r = z-1 + return [([mp.exp(nega), a], [1, r], [], G, [1, -r], [], 1/nega)] + return mpf2float(mp.hypercomb(h, [z], force_series=True)) + except mp.libmp.NoConvergence: + def h(z): + T1 = [], [1, z-1], [z], G, [], [], 0 + T2 = [-mp.exp(nega), a, z], [1, z, -1], [], G, [1], [1+z], a + return T1, T2 + return mpf2float(mp.hypercomb(h, [z], maxterms=maxterms)) + + +def main(): + t0 = time() + # It would be nice to have data for larger values, but either this + # requires prohibitively large precision (dps > 800) or mpmath has + # a bug. For example, gammainc(1e20, 1e20, dps=800) returns a + # value around 0.03, while the true value should be close to 0.5 + # (DLMF 8.12.15). + print(__doc__) + pwd = os.path.dirname(__file__) + r = np.logspace(4, 14, 30) + ltheta = np.logspace(np.log10(pi/4), np.log10(np.arctan(0.6)), 30) + utheta = np.logspace(np.log10(pi/4), np.log10(np.arctan(1.4)), 30) + + regimes = [(gammainc, ltheta), (gammaincc, utheta)] + for func, theta in regimes: + rg, thetag = np.meshgrid(r, theta) + a, x = rg*np.cos(thetag), rg*np.sin(thetag) + a, x = a.flatten(), x.flatten() + dataset = [] + for i, (a0, x0) in enumerate(zip(a, x)): + if func == gammaincc: + # Exploit the fast integer path in gammaincc whenever + # possible so that the computation doesn't take too + # long + a0, x0 = np.floor(a0), np.floor(x0) + dataset.append((a0, x0, func(a0, x0))) + dataset = np.array(dataset) + filename = os.path.join(pwd, '..', 'tests', 'data', 'local', + f'{func.__name__}.txt') + np.savetxt(filename, dataset) + + print(f"{(time() - t0)/60} minutes elapsed") + + +if __name__ == "__main__": + main() diff --git a/llava_next/lib/python3.10/site-packages/scipy/special/_precompute/loggamma.py b/llava_next/lib/python3.10/site-packages/scipy/special/_precompute/loggamma.py new file mode 100644 index 0000000000000000000000000000000000000000..74051ac7b46c70dc01919a362d05a8bbbe11333a --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/scipy/special/_precompute/loggamma.py @@ -0,0 +1,43 @@ +"""Precompute series coefficients for log-Gamma.""" + +try: + import mpmath +except ImportError: + pass + + +def stirling_series(N): + with mpmath.workdps(100): + coeffs = [mpmath.bernoulli(2*n)/(2*n*(2*n - 1)) + for n in range(1, N + 1)] + return coeffs + + +def taylor_series_at_1(N): + coeffs = [] + with mpmath.workdps(100): + coeffs.append(-mpmath.euler) + for n in range(2, N + 1): + coeffs.append((-1)**n*mpmath.zeta(n)/n) + return coeffs + + +def main(): + print(__doc__) + print() + stirling_coeffs = [mpmath.nstr(x, 20, min_fixed=0, max_fixed=0) + for x in stirling_series(8)[::-1]] + taylor_coeffs = [mpmath.nstr(x, 20, min_fixed=0, max_fixed=0) + for x in taylor_series_at_1(23)[::-1]] + print("Stirling series coefficients") + print("----------------------------") + print("\n".join(stirling_coeffs)) + print() + print("Taylor series coefficients") + print("--------------------------") + print("\n".join(taylor_coeffs)) + print() + + +if __name__ == '__main__': + main() diff --git a/llava_next/lib/python3.10/site-packages/scipy/special/_precompute/struve_convergence.py b/llava_next/lib/python3.10/site-packages/scipy/special/_precompute/struve_convergence.py new file mode 100644 index 0000000000000000000000000000000000000000..dbf6009368540dbf603b61f5b72510f0acd1a65b --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/scipy/special/_precompute/struve_convergence.py @@ -0,0 +1,131 @@ +""" +Convergence regions of the expansions used in ``struve.c`` + +Note that for v >> z both functions tend rapidly to 0, +and for v << -z, they tend to infinity. + +The floating-point functions over/underflow in the lower left and right +corners of the figure. + + +Figure legend +============= + +Red region + Power series is close (1e-12) to the mpmath result + +Blue region + Asymptotic series is close to the mpmath result + +Green region + Bessel series is close to the mpmath result + +Dotted colored lines + Boundaries of the regions + +Solid colored lines + Boundaries estimated by the routine itself. These will be used + for determining which of the results to use. + +Black dashed line + The line z = 0.7*|v| + 12 + +""" +import numpy as np +import matplotlib.pyplot as plt + +import mpmath + + +def err_metric(a, b, atol=1e-290): + m = abs(a - b) / (atol + abs(b)) + m[np.isinf(b) & (a == b)] = 0 + return m + + +def do_plot(is_h=True): + from scipy.special._ufuncs import (_struve_power_series, + _struve_asymp_large_z, + _struve_bessel_series) + + vs = np.linspace(-1000, 1000, 91) + zs = np.sort(np.r_[1e-5, 1.0, np.linspace(0, 700, 91)[1:]]) + + rp = _struve_power_series(vs[:,None], zs[None,:], is_h) + ra = _struve_asymp_large_z(vs[:,None], zs[None,:], is_h) + rb = _struve_bessel_series(vs[:,None], zs[None,:], is_h) + + mpmath.mp.dps = 50 + if is_h: + def sh(v, z): + return float(mpmath.struveh(mpmath.mpf(v), mpmath.mpf(z))) + else: + def sh(v, z): + return float(mpmath.struvel(mpmath.mpf(v), mpmath.mpf(z))) + ex = np.vectorize(sh, otypes='d')(vs[:,None], zs[None,:]) + + err_a = err_metric(ra[0], ex) + 1e-300 + err_p = err_metric(rp[0], ex) + 1e-300 + err_b = err_metric(rb[0], ex) + 1e-300 + + err_est_a = abs(ra[1]/ra[0]) + err_est_p = abs(rp[1]/rp[0]) + err_est_b = abs(rb[1]/rb[0]) + + z_cutoff = 0.7*abs(vs) + 12 + + levels = [-1000, -12] + + plt.cla() + + plt.hold(1) + plt.contourf(vs, zs, np.log10(err_p).T, + levels=levels, colors=['r', 'r'], alpha=0.1) + plt.contourf(vs, zs, np.log10(err_a).T, + levels=levels, colors=['b', 'b'], alpha=0.1) + plt.contourf(vs, zs, np.log10(err_b).T, + levels=levels, colors=['g', 'g'], alpha=0.1) + + plt.contour(vs, zs, np.log10(err_p).T, + levels=levels, colors=['r', 'r'], linestyles=[':', ':']) + plt.contour(vs, zs, np.log10(err_a).T, + levels=levels, colors=['b', 'b'], linestyles=[':', ':']) + plt.contour(vs, zs, np.log10(err_b).T, + levels=levels, colors=['g', 'g'], linestyles=[':', ':']) + + lp = plt.contour(vs, zs, np.log10(err_est_p).T, + levels=levels, colors=['r', 'r'], linestyles=['-', '-']) + la = plt.contour(vs, zs, np.log10(err_est_a).T, + levels=levels, colors=['b', 'b'], linestyles=['-', '-']) + lb = plt.contour(vs, zs, np.log10(err_est_b).T, + levels=levels, colors=['g', 'g'], linestyles=['-', '-']) + + plt.clabel(lp, fmt={-1000: 'P', -12: 'P'}) + plt.clabel(la, fmt={-1000: 'A', -12: 'A'}) + plt.clabel(lb, fmt={-1000: 'B', -12: 'B'}) + + plt.plot(vs, z_cutoff, 'k--') + + plt.xlim(vs.min(), vs.max()) + plt.ylim(zs.min(), zs.max()) + + plt.xlabel('v') + plt.ylabel('z') + + +def main(): + plt.clf() + plt.subplot(121) + do_plot(True) + plt.title('Struve H') + + plt.subplot(122) + do_plot(False) + plt.title('Struve L') + + plt.savefig('struve_convergence.png') + plt.show() + + +if __name__ == "__main__": + main() diff --git a/llava_next/lib/python3.10/site-packages/scipy/special/_precompute/utils.py b/llava_next/lib/python3.10/site-packages/scipy/special/_precompute/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..55cf4083ed5e5a6628fd3316c02ce1a5ce21a92c --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/scipy/special/_precompute/utils.py @@ -0,0 +1,38 @@ +try: + import mpmath as mp +except ImportError: + pass + +try: + from sympy.abc import x +except ImportError: + pass + + +def lagrange_inversion(a): + """Given a series + + f(x) = a[1]*x + a[2]*x**2 + ... + a[n-1]*x**(n - 1), + + use the Lagrange inversion formula to compute a series + + g(x) = b[1]*x + b[2]*x**2 + ... + b[n-1]*x**(n - 1) + + so that f(g(x)) = g(f(x)) = x mod x**n. We must have a[0] = 0, so + necessarily b[0] = 0 too. + + The algorithm is naive and could be improved, but speed isn't an + issue here and it's easy to read. + + """ + n = len(a) + f = sum(a[i]*x**i for i in range(n)) + h = (x/f).series(x, 0, n).removeO() + hpower = [h**0] + for k in range(n): + hpower.append((hpower[-1]*h).expand()) + b = [mp.mpf(0)] + for k in range(1, n): + b.append(hpower[k].coeff(x, k - 1)/k) + b = [mp.mpf(x) for x in b] + return b diff --git a/llava_next/lib/python3.10/site-packages/scipy/special/_precompute/wrightomega.py b/llava_next/lib/python3.10/site-packages/scipy/special/_precompute/wrightomega.py new file mode 100644 index 0000000000000000000000000000000000000000..0bcd0345a9c1b90c45b0e9e3340ab4da4ec5c6d7 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/scipy/special/_precompute/wrightomega.py @@ -0,0 +1,41 @@ +import numpy as np + +try: + import mpmath +except ImportError: + pass + + +def mpmath_wrightomega(x): + return mpmath.lambertw(mpmath.exp(x), mpmath.mpf('-0.5')) + + +def wrightomega_series_error(x): + series = x + desired = mpmath_wrightomega(x) + return abs(series - desired) / desired + + +def wrightomega_exp_error(x): + exponential_approx = mpmath.exp(x) + desired = mpmath_wrightomega(x) + return abs(exponential_approx - desired) / desired + + +def main(): + desired_error = 2 * np.finfo(float).eps + print('Series Error') + for x in [1e5, 1e10, 1e15, 1e20]: + with mpmath.workdps(100): + error = wrightomega_series_error(x) + print(x, error, error < desired_error) + + print('Exp error') + for x in [-10, -25, -50, -100, -200, -400, -700, -740]: + with mpmath.workdps(100): + error = wrightomega_exp_error(x) + print(x, error, error < desired_error) + + +if __name__ == '__main__': + main() diff --git a/parrot/lib/python3.10/site-packages/torch/cpu/__init__.py b/parrot/lib/python3.10/site-packages/torch/cpu/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d2b8069048ccfe855e9c020b7a164719020fe362 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/torch/cpu/__init__.py @@ -0,0 +1,168 @@ +# mypy: allow-untyped-defs +r""" +This package implements abstractions found in ``torch.cuda`` +to facilitate writing device-agnostic code. +""" + +from contextlib import AbstractContextManager +from typing import Any, Optional, Union + +import torch + +from .. import device as _device +from . import amp + + +__all__ = [ + "is_available", + "synchronize", + "current_device", + "current_stream", + "stream", + "set_device", + "device_count", + "Stream", + "StreamContext", + "Event", +] + +_device_t = Union[_device, str, int, None] + + +def _is_cpu_support_avx2() -> bool: + r"""Returns a bool indicating if CPU supports AVX2.""" + return torch._C._cpu._is_cpu_support_avx2() + + +def _is_cpu_support_avx512() -> bool: + r"""Returns a bool indicating if CPU supports AVX512.""" + return torch._C._cpu._is_cpu_support_avx512() + + +def _is_cpu_support_vnni() -> bool: + r"""Returns a bool indicating if CPU supports VNNI.""" + return torch._C._cpu._is_cpu_support_vnni() + + +def is_available() -> bool: + r"""Returns a bool indicating if CPU is currently available. + + N.B. This function only exists to facilitate device-agnostic code + + """ + return True + + +def synchronize(device: _device_t = None) -> None: + r"""Waits for all kernels in all streams on the CPU device to complete. + + Args: + device (torch.device or int, optional): ignored, there's only one CPU device. + + N.B. This function only exists to facilitate device-agnostic code. + """ + + +class Stream: + """ + N.B. This class only exists to facilitate device-agnostic code + """ + + def __init__(self, priority: int = -1) -> None: + pass + + def wait_stream(self, stream) -> None: + pass + + +class Event: + def query(self) -> bool: + return True + + def record(self, stream=None) -> None: + pass + + def synchronize(self) -> None: + pass + + def wait(self, stream=None) -> None: + pass + + +_default_cpu_stream = Stream() +_current_stream = _default_cpu_stream + + +def current_stream(device: _device_t = None) -> Stream: + r"""Returns the currently selected :class:`Stream` for a given device. + + Args: + device (torch.device or int, optional): Ignored. + + N.B. This function only exists to facilitate device-agnostic code + + """ + return _current_stream + + +class StreamContext(AbstractContextManager): + r"""Context-manager that selects a given stream. + + N.B. This class only exists to facilitate device-agnostic code + + """ + + cur_stream: Optional[Stream] + + def __init__(self, stream): + self.stream = stream + self.prev_stream = _default_cpu_stream + + def __enter__(self): + cur_stream = self.stream + if cur_stream is None: + return + + global _current_stream + self.prev_stream = _current_stream + _current_stream = cur_stream + + def __exit__(self, type: Any, value: Any, traceback: Any) -> None: + cur_stream = self.stream + if cur_stream is None: + return + + global _current_stream + _current_stream = self.prev_stream + + +def stream(stream: Stream) -> AbstractContextManager: + r"""Wrapper around the Context-manager StreamContext that + selects a given stream. + + N.B. This function only exists to facilitate device-agnostic code + """ + return StreamContext(stream) + + +def device_count() -> int: + r"""Returns number of CPU devices (not cores). Always 1. + + N.B. This function only exists to facilitate device-agnostic code + """ + return 1 + + +def set_device(device: _device_t) -> None: + r"""Sets the current device, in CPU we do nothing. + + N.B. This function only exists to facilitate device-agnostic code + """ + + +def current_device() -> str: + r"""Returns current device for cpu. Always 'cpu'. + + N.B. This function only exists to facilitate device-agnostic code + """ + return "cpu" diff --git a/parrot/lib/python3.10/site-packages/torch/package/__pycache__/_digraph.cpython-310.pyc b/parrot/lib/python3.10/site-packages/torch/package/__pycache__/_digraph.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ef0f0ab7e5306ca6ad6862f2a51a8a3739b4d8e9 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/torch/package/__pycache__/_digraph.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/torch/package/__pycache__/_importlib.cpython-310.pyc b/parrot/lib/python3.10/site-packages/torch/package/__pycache__/_importlib.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ce2bdb1020d0192dda5dbc22577e1a07cebe770e Binary files /dev/null and b/parrot/lib/python3.10/site-packages/torch/package/__pycache__/_importlib.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/torch/package/__pycache__/_stdlib.cpython-310.pyc b/parrot/lib/python3.10/site-packages/torch/package/__pycache__/_stdlib.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e5b6cacd1f823760003bdd2e2b5890cb3b370dbc Binary files /dev/null and b/parrot/lib/python3.10/site-packages/torch/package/__pycache__/_stdlib.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/torch/package/__pycache__/find_file_dependencies.cpython-310.pyc b/parrot/lib/python3.10/site-packages/torch/package/__pycache__/find_file_dependencies.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d16524555f5c692c9937e6890d67bd1e565d8550 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/torch/package/__pycache__/find_file_dependencies.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/torch/package/__pycache__/package_importer.cpython-310.pyc b/parrot/lib/python3.10/site-packages/torch/package/__pycache__/package_importer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c40500513a41d1330cb4583551c473c67516b5fb Binary files /dev/null and b/parrot/lib/python3.10/site-packages/torch/package/__pycache__/package_importer.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/torch/package/_mangling.py b/parrot/lib/python3.10/site-packages/torch/package/_mangling.py new file mode 100644 index 0000000000000000000000000000000000000000..7dcf3538631f921f6f0fac6ca4284dbe12302fdd --- /dev/null +++ b/parrot/lib/python3.10/site-packages/torch/package/_mangling.py @@ -0,0 +1,63 @@ +# mypy: allow-untyped-defs +"""Import mangling. +See mangling.md for details. +""" +import re + +_mangle_index = 0 + + +class PackageMangler: + """ + Used on import, to ensure that all modules imported have a shared mangle parent. + """ + + def __init__(self): + global _mangle_index + self._mangle_index = _mangle_index + # Increment the global index + _mangle_index += 1 + # Angle brackets are used so that there is almost no chance of + # confusing this module for a real module. Plus, it is Python's + # preferred way of denoting special modules. + self._mangle_parent = f"" + + def mangle(self, name) -> str: + assert len(name) != 0 + return self._mangle_parent + "." + name + + def demangle(self, mangled: str) -> str: + """ + Note: This only demangles names that were mangled by this specific + PackageMangler. It will pass through names created by a different + PackageMangler instance. + """ + if mangled.startswith(self._mangle_parent + "."): + return mangled.partition(".")[2] + + # wasn't a mangled name + return mangled + + def parent_name(self): + return self._mangle_parent + + +def is_mangled(name: str) -> bool: + return bool(re.match(r"", name)) + + +def demangle(name: str) -> str: + """ + Note: Unlike PackageMangler.demangle, this version works on any + mangled name, irrespective of which PackageMangler created it. + """ + if is_mangled(name): + first, sep, last = name.partition(".") + # If there is only a base mangle prefix, e.g. '', + # then return an empty string. + return last if len(sep) != 0 else "" + return name + + +def get_mangle_prefix(name: str) -> str: + return name.partition(".")[0] if is_mangled(name) else name diff --git a/parrot/lib/python3.10/site-packages/torch/package/_package_pickler.py b/parrot/lib/python3.10/site-packages/torch/package/_package_pickler.py new file mode 100644 index 0000000000000000000000000000000000000000..2ac59395b73b25aaae41120f0a069ca227f61ad2 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/torch/package/_package_pickler.py @@ -0,0 +1,119 @@ +# mypy: allow-untyped-defs +"""isort:skip_file""" +from pickle import ( # type: ignore[attr-defined] + _compat_pickle, + _extension_registry, + _getattribute, + _Pickler, + EXT1, + EXT2, + EXT4, + GLOBAL, + Pickler, + PicklingError, + STACK_GLOBAL, +) +from struct import pack +from types import FunctionType + +from .importer import Importer, ObjMismatchError, ObjNotFoundError, sys_importer + + +class PackagePickler(_Pickler): + """Package-aware pickler. + + This behaves the same as a normal pickler, except it uses an `Importer` + to find objects and modules to save. + """ + + def __init__(self, importer: Importer, *args, **kwargs): + self.importer = importer + super().__init__(*args, **kwargs) + + # Make sure the dispatch table copied from _Pickler is up-to-date. + # Previous issues have been encountered where a library (e.g. dill) + # mutate _Pickler.dispatch, PackagePickler makes a copy when this lib + # is imported, then the offending library removes its dispatch entries, + # leaving PackagePickler with a stale dispatch table that may cause + # unwanted behavior. + self.dispatch = _Pickler.dispatch.copy() # type: ignore[misc] + self.dispatch[FunctionType] = PackagePickler.save_global # type: ignore[assignment] + + def save_global(self, obj, name=None): + # unfortunately the pickler code is factored in a way that + # forces us to copy/paste this function. The only change is marked + # CHANGED below. + write = self.write # type: ignore[attr-defined] + memo = self.memo # type: ignore[attr-defined] + + # CHANGED: import module from module environment instead of __import__ + try: + module_name, name = self.importer.get_name(obj, name) + except (ObjNotFoundError, ObjMismatchError) as err: + raise PicklingError(f"Can't pickle {obj}: {str(err)}") from None + + module = self.importer.import_module(module_name) + _, parent = _getattribute(module, name) + # END CHANGED + + if self.proto >= 2: # type: ignore[attr-defined] + code = _extension_registry.get((module_name, name)) + if code: + assert code > 0 + if code <= 0xFF: + write(EXT1 + pack("= 3. + if self.proto >= 4: # type: ignore[attr-defined] + self.save(module_name) # type: ignore[attr-defined] + self.save(name) # type: ignore[attr-defined] + write(STACK_GLOBAL) + elif parent is not module: + self.save_reduce(getattr, (parent, lastname)) # type: ignore[attr-defined] + elif self.proto >= 3: # type: ignore[attr-defined] + write( + GLOBAL + + bytes(module_name, "utf-8") + + b"\n" + + bytes(name, "utf-8") + + b"\n" + ) + else: + if self.fix_imports: # type: ignore[attr-defined] + r_name_mapping = _compat_pickle.REVERSE_NAME_MAPPING + r_import_mapping = _compat_pickle.REVERSE_IMPORT_MAPPING + if (module_name, name) in r_name_mapping: + module_name, name = r_name_mapping[(module_name, name)] + elif module_name in r_import_mapping: + module_name = r_import_mapping[module_name] + try: + write( + GLOBAL + + bytes(module_name, "ascii") + + b"\n" + + bytes(name, "ascii") + + b"\n" + ) + except UnicodeEncodeError: + raise PicklingError( + "can't pickle global identifier '%s.%s' using " + "pickle protocol %i" % (module, name, self.proto) # type: ignore[attr-defined] + ) from None + + self.memoize(obj) # type: ignore[attr-defined] + + +def create_pickler(data_buf, importer, protocol=4): + if importer is sys_importer: + # if we are using the normal import library system, then + # we can use the C implementation of pickle which is faster + return Pickler(data_buf, protocol=protocol) + else: + return PackagePickler(importer, data_buf, protocol=protocol) diff --git a/parrot/lib/python3.10/site-packages/torch/package/_stdlib.py b/parrot/lib/python3.10/site-packages/torch/package/_stdlib.py new file mode 100644 index 0000000000000000000000000000000000000000..2d5145b40aa701043badad77889ff50da06ad497 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/torch/package/_stdlib.py @@ -0,0 +1,465 @@ +# mypy: allow-untyped-defs +"""List of Python standard library modules. + +Sadly, there is no reliable way to tell whether a module is part of the +standard library except by comparing to a canonical list. + +This is taken from https://github.com/PyCQA/isort/tree/develop/isort/stdlibs, +which itself is sourced from the Python documentation. +""" + +import sys + + +def is_stdlib_module(module: str) -> bool: + base_module = module.partition(".")[0] + return base_module in _get_stdlib_modules() + + +def _get_stdlib_modules(): + if sys.version_info.major == 3: + if sys.version_info.minor == 8: + return stdlib3_8 + if sys.version_info.minor == 9: + return stdlib3_9 + if sys.version_info.minor >= 10: + return sys.stdlib_module_names # type: ignore[attr-defined] + elif sys.version_info.major > 3: + return sys.stdlib_module_names # type: ignore[attr-defined] + + raise RuntimeError(f"Unsupported Python version: {sys.version_info}") + + +stdlib3_8 = { + "_dummy_thread", + "_thread", + "abc", + "aifc", + "argparse", + "array", + "ast", + "asynchat", + "asyncio", + "asyncore", + "atexit", + "audioop", + "base64", + "bdb", + "binascii", + "binhex", + "bisect", + "builtins", + "bz2", + "cProfile", + "calendar", + "cgi", + "cgitb", + "chunk", + "cmath", + "cmd", + "code", + "codecs", + "codeop", + "collections", + "colorsys", + "compileall", + "concurrent", + "configparser", + "contextlib", + "contextvars", + "copy", + "copyreg", + "crypt", + "csv", + "ctypes", + "curses", + "dataclasses", + "datetime", + "dbm", + "decimal", + "difflib", + "dis", + "distutils", + "doctest", + "dummy_threading", + "email", + "encodings", + "ensurepip", + "enum", + "errno", + "faulthandler", + "fcntl", + "filecmp", + "fileinput", + "fnmatch", + "formatter", + "fractions", + "ftplib", + "functools", + "gc", + "getopt", + "getpass", + "gettext", + "glob", + "grp", + "gzip", + "hashlib", + "heapq", + "hmac", + "html", + "http", + "imaplib", + "imghdr", + "imp", + "importlib", + "inspect", + "io", + "ipaddress", + "itertools", + "json", + "keyword", + "lib2to3", + "linecache", + "locale", + "logging", + "lzma", + "mailbox", + "mailcap", + "marshal", + "math", + "mimetypes", + "mmap", + "modulefinder", + "msilib", + "msvcrt", + "multiprocessing", + "netrc", + "nis", + "nntplib", + "ntpath", + "numbers", + "operator", + "optparse", + "os", + "ossaudiodev", + "parser", + "pathlib", + "pdb", + "pickle", + "pickletools", + "pipes", + "pkgutil", + "platform", + "plistlib", + "poplib", + "posix", + "posixpath", + "pprint", + "profile", + "pstats", + "pty", + "pwd", + "py_compile", + "pyclbr", + "pydoc", + "queue", + "quopri", + "random", + "re", + "readline", + "reprlib", + "resource", + "rlcompleter", + "runpy", + "sched", + "secrets", + "select", + "selectors", + "shelve", + "shlex", + "shutil", + "signal", + "site", + "smtpd", + "smtplib", + "sndhdr", + "socket", + "socketserver", + "spwd", + "sqlite3", + "sre", + "sre_compile", + "sre_constants", + "sre_parse", + "ssl", + "stat", + "statistics", + "string", + "stringprep", + "struct", + "subprocess", + "sunau", + "symbol", + "symtable", + "sys", + "sysconfig", + "syslog", + "tabnanny", + "tarfile", + "telnetlib", + "tempfile", + "termios", + "test", + "textwrap", + "threading", + "time", + "timeit", + "tkinter", + "token", + "tokenize", + "trace", + "traceback", + "tracemalloc", + "tty", + "turtle", + "turtledemo", + "types", + "typing", + "unicodedata", + "unittest", + "urllib", + "uu", + "uuid", + "venv", + "warnings", + "wave", + "weakref", + "webbrowser", + "winreg", + "winsound", + "wsgiref", + "xdrlib", + "xml", + "xmlrpc", + "zipapp", + "zipfile", + "zipimport", + "zlib", +} + +stdlib3_9 = { + "_thread", + "abc", + "aifc", + "argparse", + "array", + "ast", + "asynchat", + "asyncio", + "asyncore", + "atexit", + "audioop", + "base64", + "bdb", + "binascii", + "binhex", + "bisect", + "builtins", + "bz2", + "cProfile", + "calendar", + "cgi", + "cgitb", + "chunk", + "cmath", + "cmd", + "code", + "codecs", + "codeop", + "collections", + "colorsys", + "compileall", + "concurrent", + "configparser", + "contextlib", + "contextvars", + "copy", + "copyreg", + "crypt", + "csv", + "ctypes", + "curses", + "dataclasses", + "datetime", + "dbm", + "decimal", + "difflib", + "dis", + "distutils", + "doctest", + "email", + "encodings", + "ensurepip", + "enum", + "errno", + "faulthandler", + "fcntl", + "filecmp", + "fileinput", + "fnmatch", + "formatter", + "fractions", + "ftplib", + "functools", + "gc", + "getopt", + "getpass", + "gettext", + "glob", + "graphlib", + "grp", + "gzip", + "hashlib", + "heapq", + "hmac", + "html", + "http", + "imaplib", + "imghdr", + "imp", + "importlib", + "inspect", + "io", + "ipaddress", + "itertools", + "json", + "keyword", + "lib2to3", + "linecache", + "locale", + "logging", + "lzma", + "mailbox", + "mailcap", + "marshal", + "math", + "mimetypes", + "mmap", + "modulefinder", + "msilib", + "msvcrt", + "multiprocessing", + "netrc", + "nis", + "nntplib", + "ntpath", + "numbers", + "operator", + "optparse", + "os", + "ossaudiodev", + "parser", + "pathlib", + "pdb", + "pickle", + "pickletools", + "pipes", + "pkgutil", + "platform", + "plistlib", + "poplib", + "posix", + "posixpath", + "pprint", + "profile", + "pstats", + "pty", + "pwd", + "py_compile", + "pyclbr", + "pydoc", + "queue", + "quopri", + "random", + "re", + "readline", + "reprlib", + "resource", + "rlcompleter", + "runpy", + "sched", + "secrets", + "select", + "selectors", + "shelve", + "shlex", + "shutil", + "signal", + "site", + "smtpd", + "smtplib", + "sndhdr", + "socket", + "socketserver", + "spwd", + "sqlite3", + "sre", + "sre_compile", + "sre_constants", + "sre_parse", + "ssl", + "stat", + "statistics", + "string", + "stringprep", + "struct", + "subprocess", + "sunau", + "symbol", + "symtable", + "sys", + "sysconfig", + "syslog", + "tabnanny", + "tarfile", + "telnetlib", + "tempfile", + "termios", + "test", + "textwrap", + "threading", + "time", + "timeit", + "tkinter", + "token", + "tokenize", + "trace", + "traceback", + "tracemalloc", + "tty", + "turtle", + "turtledemo", + "types", + "typing", + "unicodedata", + "unittest", + "urllib", + "uu", + "uuid", + "venv", + "warnings", + "wave", + "weakref", + "webbrowser", + "winreg", + "winsound", + "wsgiref", + "xdrlib", + "xml", + "xmlrpc", + "zipapp", + "zipfile", + "zipimport", + "zlib", + "zoneinfo", +} diff --git a/parrot/lib/python3.10/site-packages/torch/package/analyze/__pycache__/find_first_use_of_broken_modules.cpython-310.pyc b/parrot/lib/python3.10/site-packages/torch/package/analyze/__pycache__/find_first_use_of_broken_modules.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..024dafe5f4f687c1515faeb70d0c472bbff6ad62 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/torch/package/analyze/__pycache__/find_first_use_of_broken_modules.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/torch/package/analyze/__pycache__/is_from_package.cpython-310.pyc b/parrot/lib/python3.10/site-packages/torch/package/analyze/__pycache__/is_from_package.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2800f71af964d906dbb8196ab8ff303368d7a70e Binary files /dev/null and b/parrot/lib/python3.10/site-packages/torch/package/analyze/__pycache__/is_from_package.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/torch/package/analyze/__pycache__/trace_dependencies.cpython-310.pyc b/parrot/lib/python3.10/site-packages/torch/package/analyze/__pycache__/trace_dependencies.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0d85ab791f18113fb493ae7e4055d3495eed84db Binary files /dev/null and b/parrot/lib/python3.10/site-packages/torch/package/analyze/__pycache__/trace_dependencies.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/torch/package/analyze/is_from_package.py b/parrot/lib/python3.10/site-packages/torch/package/analyze/is_from_package.py new file mode 100644 index 0000000000000000000000000000000000000000..82ff5896b6ffcc2dcb7b15dc169729aceb8b1d75 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/torch/package/analyze/is_from_package.py @@ -0,0 +1,16 @@ +from types import ModuleType +from typing import Any + +from .._mangling import is_mangled + + +def is_from_package(obj: Any) -> bool: + """ + Return whether an object was loaded from a package. + + Note: packaged objects from externed modules will return ``False``. + """ + if type(obj) == ModuleType: + return is_mangled(obj.__name__) + else: + return is_mangled(type(obj).__module__) diff --git a/parrot/lib/python3.10/site-packages/torch/package/package_importer.py b/parrot/lib/python3.10/site-packages/torch/package/package_importer.py new file mode 100644 index 0000000000000000000000000000000000000000..1a103ab6c5c91e9fa7e39376a14e1cca332d8933 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/torch/package/package_importer.py @@ -0,0 +1,773 @@ +# mypy: allow-untyped-defs +import builtins +import importlib +import importlib.machinery +import inspect +import io +import linecache +import os +import types +from contextlib import contextmanager +from typing import ( + Any, + BinaryIO, + Callable, + cast, + Dict, + Iterable, + List, + Optional, + TYPE_CHECKING, + Union, +) +from weakref import WeakValueDictionary + +import torch +from torch.serialization import _get_restore_location, _maybe_decode_ascii + +from ._directory_reader import DirectoryReader +from ._importlib import ( + _calc___package__, + _normalize_line_endings, + _normalize_path, + _resolve_name, + _sanity_check, +) +from ._mangling import demangle, PackageMangler +from ._package_unpickler import PackageUnpickler +from .file_structure_representation import _create_directory_from_file_list, Directory +from .importer import Importer + +if TYPE_CHECKING: + from .glob_group import GlobPattern + +__all__ = ["PackageImporter"] + + +# This is a list of imports that are implicitly allowed even if they haven't +# been marked as extern. This is to work around the fact that Torch implicitly +# depends on numpy and package can't track it. +# https://github.com/pytorch/MultiPy/issues/46 +IMPLICIT_IMPORT_ALLOWLIST: Iterable[str] = [ + "numpy", + "numpy.core", + "numpy.core._multiarray_umath", + # FX GraphModule might depend on builtins module and users usually + # don't extern builtins. Here we import it here by default. + "builtins", +] + + +class PackageImporter(Importer): + """Importers allow you to load code written to packages by :class:`PackageExporter`. + Code is loaded in a hermetic way, using files from the package + rather than the normal python import system. This allows + for the packaging of PyTorch model code and data so that it can be run + on a server or used in the future for transfer learning. + + The importer for packages ensures that code in the module can only be loaded from + within the package, except for modules explicitly listed as external during export. + The file ``extern_modules`` in the zip archive lists all the modules that a package externally depends on. + This prevents "implicit" dependencies where the package runs locally because it is importing + a locally-installed package, but then fails when the package is copied to another machine. + """ + + """The dictionary of already loaded modules from this package, equivalent to ``sys.modules`` but + local to this importer. + """ + + modules: Dict[str, types.ModuleType] + + def __init__( + self, + file_or_buffer: Union[str, torch._C.PyTorchFileReader, os.PathLike, BinaryIO], + module_allowed: Callable[[str], bool] = lambda module_name: True, + ): + """Open ``file_or_buffer`` for importing. This checks that the imported package only requires modules + allowed by ``module_allowed`` + + Args: + file_or_buffer: a file-like object (has to implement :meth:`read`, :meth:`readline`, :meth:`tell`, and :meth:`seek`), + a string, or an ``os.PathLike`` object containing a filename. + module_allowed (Callable[[str], bool], optional): A method to determine if a externally provided module + should be allowed. Can be used to ensure packages loaded do not depend on modules that the server + does not support. Defaults to allowing anything. + + Raises: + ImportError: If the package will use a disallowed module. + """ + torch._C._log_api_usage_once("torch.package.PackageImporter") + + self.zip_reader: Any + if isinstance(file_or_buffer, torch._C.PyTorchFileReader): + self.filename = "" + self.zip_reader = file_or_buffer + elif isinstance(file_or_buffer, (os.PathLike, str)): + self.filename = os.fspath(file_or_buffer) + if not os.path.isdir(self.filename): + self.zip_reader = torch._C.PyTorchFileReader(self.filename) + else: + self.zip_reader = DirectoryReader(self.filename) + else: + self.filename = "" + self.zip_reader = torch._C.PyTorchFileReader(file_or_buffer) + + torch._C._log_api_usage_metadata( + "torch.package.PackageImporter.metadata", + { + "serialization_id": self.zip_reader.serialization_id(), + "file_name": self.filename, + }, + ) + + self.root = _PackageNode(None) + self.modules = {} + self.extern_modules = self._read_extern() + + for extern_module in self.extern_modules: + if not module_allowed(extern_module): + raise ImportError( + f"package '{file_or_buffer}' needs the external module '{extern_module}' " + f"but that module has been disallowed" + ) + self._add_extern(extern_module) + + for fname in self.zip_reader.get_all_records(): + self._add_file(fname) + + self.patched_builtins = builtins.__dict__.copy() + self.patched_builtins["__import__"] = self.__import__ + # Allow packaged modules to reference their PackageImporter + self.modules["torch_package_importer"] = self # type: ignore[assignment] + + self._mangler = PackageMangler() + + # used for reduce deserializaiton + self.storage_context: Any = None + self.last_map_location = None + + # used for torch.serialization._load + self.Unpickler = lambda *args, **kwargs: PackageUnpickler(self, *args, **kwargs) + + def import_module(self, name: str, package=None): + """Load a module from the package if it hasn't already been loaded, and then return + the module. Modules are loaded locally + to the importer and will appear in ``self.modules`` rather than ``sys.modules``. + + Args: + name (str): Fully qualified name of the module to load. + package ([type], optional): Unused, but present to match the signature of importlib.import_module. Defaults to ``None``. + + Returns: + types.ModuleType: The (possibly already) loaded module. + """ + # We should always be able to support importing modules from this package. + # This is to support something like: + # obj = importer.load_pickle(...) + # importer.import_module(obj.__module__) <- this string will be mangled + # + # Note that _mangler.demangle will not demangle any module names + # produced by a different PackageImporter instance. + name = self._mangler.demangle(name) + + return self._gcd_import(name) + + def load_binary(self, package: str, resource: str) -> bytes: + """Load raw bytes. + + Args: + package (str): The name of module package (e.g. ``"my_package.my_subpackage"``). + resource (str): The unique name for the resource. + + Returns: + bytes: The loaded data. + """ + + path = self._zipfile_path(package, resource) + return self.zip_reader.get_record(path) + + def load_text( + self, + package: str, + resource: str, + encoding: str = "utf-8", + errors: str = "strict", + ) -> str: + """Load a string. + + Args: + package (str): The name of module package (e.g. ``"my_package.my_subpackage"``). + resource (str): The unique name for the resource. + encoding (str, optional): Passed to ``decode``. Defaults to ``'utf-8'``. + errors (str, optional): Passed to ``decode``. Defaults to ``'strict'``. + + Returns: + str: The loaded text. + """ + data = self.load_binary(package, resource) + return data.decode(encoding, errors) + + def load_pickle(self, package: str, resource: str, map_location=None) -> Any: + """Unpickles the resource from the package, loading any modules that are needed to construct the objects + using :meth:`import_module`. + + Args: + package (str): The name of module package (e.g. ``"my_package.my_subpackage"``). + resource (str): The unique name for the resource. + map_location: Passed to `torch.load` to determine how tensors are mapped to devices. Defaults to ``None``. + + Returns: + Any: The unpickled object. + """ + pickle_file = self._zipfile_path(package, resource) + restore_location = _get_restore_location(map_location) + loaded_storages = {} + loaded_reduces = {} + storage_context = torch._C.DeserializationStorageContext() + + def load_tensor(dtype, size, key, location, restore_location): + name = f"{key}.storage" + + if storage_context.has_storage(name): + storage = storage_context.get_storage(name, dtype)._typed_storage() + else: + tensor = self.zip_reader.get_storage_from_record( + ".data/" + name, size, dtype + ) + if isinstance(self.zip_reader, torch._C.PyTorchFileReader): + storage_context.add_storage(name, tensor) + storage = tensor._typed_storage() + loaded_storages[key] = restore_location(storage, location) + + def persistent_load(saved_id): + assert isinstance(saved_id, tuple) + typename = _maybe_decode_ascii(saved_id[0]) + data = saved_id[1:] + + if typename == "storage": + storage_type, key, location, size = data + dtype = storage_type.dtype + + if key not in loaded_storages: + load_tensor( + dtype, + size, + key, + _maybe_decode_ascii(location), + restore_location, + ) + storage = loaded_storages[key] + # TODO: Once we decide to break serialization FC, we can + # stop wrapping with TypedStorage + return torch.storage.TypedStorage( + wrap_storage=storage._untyped_storage, dtype=dtype, _internal=True + ) + elif typename == "reduce_package": + # to fix BC breaking change, objects on this load path + # will be loaded multiple times erroneously + if len(data) == 2: + func, args = data + return func(self, *args) + reduce_id, func, args = data + if reduce_id not in loaded_reduces: + loaded_reduces[reduce_id] = func(self, *args) + return loaded_reduces[reduce_id] + else: + f"Unknown typename for persistent_load, expected 'storage' or 'reduce_package' but got '{typename}'" + + # Load the data (which may in turn use `persistent_load` to load tensors) + data_file = io.BytesIO(self.zip_reader.get_record(pickle_file)) + unpickler = self.Unpickler(data_file) + unpickler.persistent_load = persistent_load # type: ignore[assignment] + + @contextmanager + def set_deserialization_context(): + # to let reduce_package access deserializaiton context + self.storage_context = storage_context + self.last_map_location = map_location + try: + yield + finally: + self.storage_context = None + self.last_map_location = None + + with set_deserialization_context(): + result = unpickler.load() + + # TODO from zdevito: + # This stateful weird function will need to be removed in our efforts + # to unify the format. It has a race condition if multiple python + # threads try to read independent files + torch._utils._validate_loaded_sparse_tensors() + + return result + + def id(self): + """ + Returns internal identifier that torch.package uses to distinguish :class:`PackageImporter` instances. + Looks like:: + + + """ + return self._mangler.parent_name() + + def file_structure( + self, *, include: "GlobPattern" = "**", exclude: "GlobPattern" = () + ) -> Directory: + """Returns a file structure representation of package's zipfile. + + Args: + include (Union[List[str], str]): An optional string e.g. ``"my_package.my_subpackage"``, or optional list of strings + for the names of the files to be included in the zipfile representation. This can also be + a glob-style pattern, as described in :meth:`PackageExporter.mock` + + exclude (Union[List[str], str]): An optional pattern that excludes files whose name match the pattern. + + Returns: + :class:`Directory` + """ + return _create_directory_from_file_list( + self.filename, self.zip_reader.get_all_records(), include, exclude + ) + + def python_version(self): + """Returns the version of python that was used to create this package. + + Note: this function is experimental and not Forward Compatible. The plan is to move this into a lock + file later on. + + Returns: + :class:`Optional[str]` a python version e.g. 3.8.9 or None if no version was stored with this package + """ + python_version_path = ".data/python_version" + return ( + self.zip_reader.get_record(python_version_path).decode("utf-8").strip() + if self.zip_reader.has_record(python_version_path) + else None + ) + + def _read_extern(self): + return ( + self.zip_reader.get_record(".data/extern_modules") + .decode("utf-8") + .splitlines(keepends=False) + ) + + def _make_module( + self, name: str, filename: Optional[str], is_package: bool, parent: str + ): + mangled_filename = self._mangler.mangle(filename) if filename else None + spec = importlib.machinery.ModuleSpec( + name, + self, # type: ignore[arg-type] + origin="", + is_package=is_package, + ) + module = importlib.util.module_from_spec(spec) + self.modules[name] = module + module.__name__ = self._mangler.mangle(name) + ns = module.__dict__ + ns["__spec__"] = spec + ns["__loader__"] = self + ns["__file__"] = mangled_filename + ns["__cached__"] = None + ns["__builtins__"] = self.patched_builtins + ns["__torch_package__"] = True + + # Add this module to our private global registry. It should be unique due to mangling. + assert module.__name__ not in _package_imported_modules + _package_imported_modules[module.__name__] = module + + # pre-emptively install on the parent to prevent IMPORT_FROM from trying to + # access sys.modules + self._install_on_parent(parent, name, module) + + if filename is not None: + assert mangled_filename is not None + # pre-emptively install the source in `linecache` so that stack traces, + # `inspect`, etc. work. + assert filename not in linecache.cache # type: ignore[attr-defined] + linecache.lazycache(mangled_filename, ns) + + code = self._compile_source(filename, mangled_filename) + exec(code, ns) + + return module + + def _load_module(self, name: str, parent: str): + cur: _PathNode = self.root + for atom in name.split("."): + if not isinstance(cur, _PackageNode) or atom not in cur.children: + if name in IMPLICIT_IMPORT_ALLOWLIST: + module = self.modules[name] = importlib.import_module(name) + return module + raise ModuleNotFoundError( + f'No module named "{name}" in self-contained archive "{self.filename}"' + f" and the module is also not in the list of allowed external modules: {self.extern_modules}", + name=name, + ) + cur = cur.children[atom] + if isinstance(cur, _ExternNode): + module = self.modules[name] = importlib.import_module(name) + return module + return self._make_module(name, cur.source_file, isinstance(cur, _PackageNode), parent) # type: ignore[attr-defined] + + def _compile_source(self, fullpath: str, mangled_filename: str): + source = self.zip_reader.get_record(fullpath) + source = _normalize_line_endings(source) + return compile(source, mangled_filename, "exec", dont_inherit=True) + + # note: named `get_source` so that linecache can find the source + # when this is the __loader__ of a module. + def get_source(self, module_name) -> str: + # linecache calls `get_source` with the `module.__name__` as the argument, so we must demangle it here. + module = self.import_module(demangle(module_name)) + return self.zip_reader.get_record(demangle(module.__file__)).decode("utf-8") + + # note: named `get_resource_reader` so that importlib.resources can find it. + # This is otherwise considered an internal method. + def get_resource_reader(self, fullname): + try: + package = self._get_package(fullname) + except ImportError: + return None + if package.__loader__ is not self: + return None + return _PackageResourceReader(self, fullname) + + def _install_on_parent(self, parent: str, name: str, module: types.ModuleType): + if not parent: + return + # Set the module as an attribute on its parent. + parent_module = self.modules[parent] + if parent_module.__loader__ is self: + setattr(parent_module, name.rpartition(".")[2], module) + + # note: copied from cpython's import code, with call to create module replaced with _make_module + def _do_find_and_load(self, name): + path = None + parent = name.rpartition(".")[0] + module_name_no_parent = name.rpartition(".")[-1] + if parent: + if parent not in self.modules: + self._gcd_import(parent) + # Crazy side-effects! + if name in self.modules: + return self.modules[name] + parent_module = self.modules[parent] + + try: + path = parent_module.__path__ # type: ignore[attr-defined] + + except AttributeError: + # when we attempt to import a package only containing pybinded files, + # the parent directory isn't always a package as defined by python, + # so we search if the package is actually there or not before calling the error. + if isinstance( + parent_module.__loader__, + importlib.machinery.ExtensionFileLoader, + ): + if name not in self.extern_modules: + msg = ( + _ERR_MSG + + "; {!r} is a c extension module which was not externed. C extension modules \ + need to be externed by the PackageExporter in order to be used as we do not support interning them.}." + ).format(name, name) + raise ModuleNotFoundError(msg, name=name) from None + if not isinstance( + parent_module.__dict__.get(module_name_no_parent), + types.ModuleType, + ): + msg = ( + _ERR_MSG + + "; {!r} is a c extension package which does not contain {!r}." + ).format(name, parent, name) + raise ModuleNotFoundError(msg, name=name) from None + else: + msg = (_ERR_MSG + "; {!r} is not a package").format(name, parent) + raise ModuleNotFoundError(msg, name=name) from None + + module = self._load_module(name, parent) + + self._install_on_parent(parent, name, module) + + return module + + # note: copied from cpython's import code + def _find_and_load(self, name): + module = self.modules.get(name, _NEEDS_LOADING) + if module is _NEEDS_LOADING: + return self._do_find_and_load(name) + + if module is None: + message = f"import of {name} halted; None in sys.modules" + raise ModuleNotFoundError(message, name=name) + + # To handle https://github.com/pytorch/pytorch/issues/57490, where std's + # creation of fake submodules via the hacking of sys.modules is not import + # friendly + if name == "os": + self.modules["os.path"] = cast(Any, module).path + elif name == "typing": + self.modules["typing.io"] = cast(Any, module).io + self.modules["typing.re"] = cast(Any, module).re + + return module + + def _gcd_import(self, name, package=None, level=0): + """Import and return the module based on its name, the package the call is + being made from, and the level adjustment. + + This function represents the greatest common denominator of functionality + between import_module and __import__. This includes setting __package__ if + the loader did not. + + """ + _sanity_check(name, package, level) + if level > 0: + name = _resolve_name(name, package, level) + + return self._find_and_load(name) + + # note: copied from cpython's import code + def _handle_fromlist(self, module, fromlist, *, recursive=False): + """Figure out what __import__ should return. + + The import_ parameter is a callable which takes the name of module to + import. It is required to decouple the function from assuming importlib's + import implementation is desired. + + """ + module_name = demangle(module.__name__) + # The hell that is fromlist ... + # If a package was imported, try to import stuff from fromlist. + if hasattr(module, "__path__"): + for x in fromlist: + if not isinstance(x, str): + if recursive: + where = module_name + ".__all__" + else: + where = "``from list''" + raise TypeError( + f"Item in {where} must be str, " f"not {type(x).__name__}" + ) + elif x == "*": + if not recursive and hasattr(module, "__all__"): + self._handle_fromlist(module, module.__all__, recursive=True) + elif not hasattr(module, x): + from_name = f"{module_name}.{x}" + try: + self._gcd_import(from_name) + except ModuleNotFoundError as exc: + # Backwards-compatibility dictates we ignore failed + # imports triggered by fromlist for modules that don't + # exist. + if ( + exc.name == from_name + and self.modules.get(from_name, _NEEDS_LOADING) is not None + ): + continue + raise + return module + + def __import__(self, name, globals=None, locals=None, fromlist=(), level=0): + if level == 0: + module = self._gcd_import(name) + else: + globals_ = globals if globals is not None else {} + package = _calc___package__(globals_) + module = self._gcd_import(name, package, level) + if not fromlist: + # Return up to the first dot in 'name'. This is complicated by the fact + # that 'name' may be relative. + if level == 0: + return self._gcd_import(name.partition(".")[0]) + elif not name: + return module + else: + # Figure out where to slice the module's name up to the first dot + # in 'name'. + cut_off = len(name) - len(name.partition(".")[0]) + # Slice end needs to be positive to alleviate need to special-case + # when ``'.' not in name``. + module_name = demangle(module.__name__) + return self.modules[module_name[: len(module_name) - cut_off]] + else: + return self._handle_fromlist(module, fromlist) + + def _get_package(self, package): + """Take a package name or module object and return the module. + + If a name, the module is imported. If the passed or imported module + object is not a package, raise an exception. + """ + if hasattr(package, "__spec__"): + if package.__spec__.submodule_search_locations is None: + raise TypeError(f"{package.__spec__.name!r} is not a package") + else: + return package + else: + module = self.import_module(package) + if module.__spec__.submodule_search_locations is None: + raise TypeError(f"{package!r} is not a package") + else: + return module + + def _zipfile_path(self, package, resource=None): + package = self._get_package(package) + assert package.__loader__ is self + name = demangle(package.__name__) + if resource is not None: + resource = _normalize_path(resource) + return f"{name.replace('.', '/')}/{resource}" + else: + return f"{name.replace('.', '/')}" + + def _get_or_create_package( + self, atoms: List[str] + ) -> "Union[_PackageNode, _ExternNode]": + cur = self.root + for i, atom in enumerate(atoms): + node = cur.children.get(atom, None) + if node is None: + node = cur.children[atom] = _PackageNode(None) + if isinstance(node, _ExternNode): + return node + if isinstance(node, _ModuleNode): + name = ".".join(atoms[:i]) + raise ImportError( + f"inconsistent module structure. module {name} is not a package, but has submodules" + ) + assert isinstance(node, _PackageNode) + cur = node + return cur + + def _add_file(self, filename: str): + """Assembles a Python module out of the given file. Will ignore files in the .data directory. + + Args: + filename (str): the name of the file inside of the package archive to be added + """ + *prefix, last = filename.split("/") + if len(prefix) > 1 and prefix[0] == ".data": + return + package = self._get_or_create_package(prefix) + if isinstance(package, _ExternNode): + raise ImportError( + f"inconsistent module structure. package contains a module file {filename}" + f" that is a subpackage of a module marked external." + ) + if last == "__init__.py": + package.source_file = filename + elif last.endswith(".py"): + package_name = last[: -len(".py")] + package.children[package_name] = _ModuleNode(filename) + + def _add_extern(self, extern_name: str): + *prefix, last = extern_name.split(".") + package = self._get_or_create_package(prefix) + if isinstance(package, _ExternNode): + return # the shorter extern covers this extern case + package.children[last] = _ExternNode() + + +_NEEDS_LOADING = object() +_ERR_MSG_PREFIX = "No module named " +_ERR_MSG = _ERR_MSG_PREFIX + "{!r}" + + +class _PathNode: + pass + + +class _PackageNode(_PathNode): + def __init__(self, source_file: Optional[str]): + self.source_file = source_file + self.children: Dict[str, _PathNode] = {} + + +class _ModuleNode(_PathNode): + __slots__ = ["source_file"] + + def __init__(self, source_file: str): + self.source_file = source_file + + +class _ExternNode(_PathNode): + pass + + +# A private global registry of all modules that have been package-imported. +_package_imported_modules: WeakValueDictionary = WeakValueDictionary() + +# `inspect` by default only looks in `sys.modules` to find source files for classes. +# Patch it to check our private registry of package-imported modules as well. +_orig_getfile = inspect.getfile + + +def _patched_getfile(object): + if inspect.isclass(object): + if object.__module__ in _package_imported_modules: + return _package_imported_modules[object.__module__].__file__ + return _orig_getfile(object) + + +inspect.getfile = _patched_getfile + + +class _PackageResourceReader: + """Private class used to support PackageImporter.get_resource_reader(). + + Confirms to the importlib.abc.ResourceReader interface. Allowed to access + the innards of PackageImporter. + """ + + def __init__(self, importer, fullname): + self.importer = importer + self.fullname = fullname + + def open_resource(self, resource): + from io import BytesIO + + return BytesIO(self.importer.load_binary(self.fullname, resource)) + + def resource_path(self, resource): + # The contract for resource_path is that it either returns a concrete + # file system path or raises FileNotFoundError. + if isinstance( + self.importer.zip_reader, DirectoryReader + ) and self.importer.zip_reader.has_record( + os.path.join(self.fullname, resource) + ): + return os.path.join( + self.importer.zip_reader.directory, self.fullname, resource + ) + raise FileNotFoundError + + def is_resource(self, name): + path = self.importer._zipfile_path(self.fullname, name) + return self.importer.zip_reader.has_record(path) + + def contents(self): + from pathlib import Path + + filename = self.fullname.replace(".", "/") + + fullname_path = Path(self.importer._zipfile_path(self.fullname)) + files = self.importer.zip_reader.get_all_records() + subdirs_seen = set() + for filename in files: + try: + relative = Path(filename).relative_to(fullname_path) + except ValueError: + continue + # If the path of the file (which is relative to the top of the zip + # namespace), relative to the package given when the resource + # reader was created, has a parent, then it's a name in a + # subdirectory and thus we skip it. + parent_name = relative.parent.name + if len(parent_name) == 0: + yield relative.name + elif parent_name not in subdirs_seen: + subdirs_seen.add(parent_name) + yield parent_name