Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupport News AboutSign UpSign In
| Download
Views: 234

Some experiments in linear programming (MILP)

Example 1:
        maximize:x+y+3zsubject to:x+2y45zy8x,y,z0\begin{array}{ll} \mbox{maximize:} & x+y+3z \\ \mbox{subject to:} & x+2y \le 4 \\ & 5z-y \le 8 \\ & x, y, z \ge 0 \end{array}
# Declare a MILP object, say, r. r = MixedIntegerLinearProgram() # Declare the variables associated with r. # Note that we're also imposing the nonnegativity constraint simultaneously. x = r.new_variable(real=True, nonnegative=True) # Define the objective function. r.set_objective(x[1]+x[2]+3*x[3]) # Impose the remaining constraints. r.add_constraint(x[1]+2*x[2] <= 4) r.add_constraint(5*x[3]-x[2] <= 8) # solve and print results a = r.solve() print "maximum value =", a b = r.get_values(x) print "values of variables are =", b
maximum value = 8.8 values of variables are = {1: 4.0, 2: 0.0, 3: 1.6}
Example 2:

The next example is an attempt to setup an optimization problem for the HAAI test case along lines suggested by อาจารย์พัชรี.

# Define channel capacities along each edge in the form of a dictionary: c = {(0,1):7, (1,2):4, (1,3):4, (2,4):2, (4,6):4, (3,5):4, (5,6):2.5, (5,7):2.5, (6,8):5, (7,9):3} # Test whether it works correctly: c[(5,7)] # For minimization problems, set the input variable "maximization" to False r = MixedIntegerLinearProgram(maximization=False) # Declare the variables associated with r. # I'll use "p" for pumping, and "f" for flow rate p = r.new_variable(real=True, nonnegative=True) f = r.new_variable(real=True, nonnegative=True) # Define the objective function. r.set_objective(p[(0,1)]+p[(1,2)]+p[(1,3)]+p[(2,4)]+p[(4,6)]+p[(3,5)]+p[(5,6)]+p[(5,7)]+p[(6,8)]+p[(7,9)]) # Impose the node/flow constraints. r.add_constraint( f[(0,1)] == f[(1,2)]+f[(1,3)] ) r.add_constraint( f[(1,2)] == f[(2,4)] ) r.add_constraint( f[(1,3)] == f[(3,5)] ) r.add_constraint( f[(2,4)] == f[(4,6)] ) r.add_constraint( f[(3,5)] == f[(5,6)]+f[(5,7)] ) r.add_constraint( f[(4,6)]+f[(5,6)] == f[(6,8)] ) r.add_constraint( f[(5,7)] == f[(7,9)] ) # Impose capacity constraints. r.add_constraint( f[(0,1)] <= c[(0,1)] ) r.add_constraint( f[(1,2)] <= c[(1,2)] ) r.add_constraint( f[(1,3)] <= c[(1,3)] ) r.add_constraint( f[(2,4)] <= c[(2,4)] ) r.add_constraint( f[(4,6)] <= c[(4,6)] ) r.add_constraint( f[(3,5)] <= c[(3,5)] ) r.add_constraint( f[(5,6)] <= c[(5,6)] ) r.add_constraint( f[(5,7)] <= c[(5,7)] ) r.add_constraint( f[(6,8)] <= c[(6,8)] ) r.add_constraint( f[(7,9)] <= c[(7,9)] ) r.add_constraint( f[(0,1)] >= 6 ) #r.add_constraint( f[(0,1)] <= min(7,4) ) # Attempt to impose IF-condition in the form of a "maximum" condition #r.add_constraint( "p[(0,1)] == max(0, f[(0,1)]-c[(0,1)])" ) #r.add_constraint( p[(0,1)] == ( (f[(0,1)]-c[(0,1)]) + abs(f[(0,1)]-c[(0,1)]) )/2 ) # solve and print results a = r.solve() print "minimum value =", a b = r.get_values(p) c = r.get_values(f) print "values of pump variables are =", b print "values of flow variables are =", c
2.50000000000000 minimum value = 0.0 values of pump variables are = {(0, 1): 0.0, (1, 2): 0.0, (1, 3): 0.0, (4, 6): 0.0, (5, 6): 0.0, (5, 7): 0.0, (3, 5): 0.0, (7, 9): 0.0, (2, 4): 0.0, (6, 8): 0.0} values of flow variables are = {(0, 1): 6.0, (1, 2): 2.0, (1, 3): 4.0, (4, 6): 2.0, (5, 6): 2.5, (5, 7): 1.5, (3, 5): 4.0, (7, 9): 1.5, (2, 4): 2.0, (6, 8): 4.5}
%python import numpy as np from scipy.optimize import minimize n = 10 # n denotes the number of edges in the network. # Setup strategy: There are 20 variables in the optimization problem. # Since there are 10 edges, we have 10 pumping rates, and 10 flow rates. # The objective function consists of the sum of the pumping rates, # which we want to minimize. # The constraints are split into two groups: (1) bounds, and (2) constraints. # The maximum flow capacity and pumping capacity are enforced as "bounds". # Flow continuity conditions at each node are enforced as "constraints". # Define the objective function def objective(p): return sum(p[i] for i in range(10)) # Initial guess for the solution p0 = np.zeros(20) # Define flow continuity constraints at the nodes cons = ({'type':'eq', 'fun': lambda x: x[10]-x[11]-x[12]}, {'type':'eq', 'fun': lambda x: x[11]-x[13]}, {'type':'eq', 'fun': lambda x: x[12]-x[15]}, {'type':'eq', 'fun': lambda x: x[13]-x[14]}, {'type':'eq', 'fun': lambda x: x[15]-x[16]-x[17]}, {'type':'eq', 'fun': lambda x: x[14]+x[16]-x[18]}, {'type':'eq', 'fun': lambda x: x[17]-x[19]}, {'type':'ineq', 'fun': lambda x: x[10]-6.0}) # Define maximum flow capacities, and setup as bounds c = {(0):7, (1):4, (2):4, (3):2, (4):4, (5):4, (6):2.5, (7):2.5, (8):5, (9):3} bnds = ((0,5), (0,5), (0,5), (0,5), (0,5), (0,5), (0,5), (0,5), (0,5), (0,5), (0,c[(0)]), (0,c[(1)]), (0,c[(2)]), (0,c[(3)]), (0,c[(4)]), (0,c[(5)]), (0,c[(6)]), (0,c[(7)]), (0,c[(8)]), (0,c[(9)]) ) # Call "minimize" and get computed solution res = minimize(objective, p0, method='SLSQP', bounds=bnds, constraints=cons) print res
fun: 2.9874882360387023e-13 jac: array([ 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]) message: 'Optimization terminated successfully.' nfev: 23 nit: 1 njev: 1 status: 0 success: True x: array([ 2.87162428e-14, 2.92391519e-14, 3.01931678e-14, 3.01082838e-14, 2.97520650e-14, 3.00483403e-14, 3.05414624e-14, 3.33066907e-14, 2.75335310e-14, 2.93098879e-14, 6.00000000e+00, 2.00000000e+00, 4.00000000e+00, 2.00000000e+00, 2.00000000e+00, 4.00000000e+00, 1.50000000e+00, 2.50000000e+00, 3.50000000e+00, 2.50000000e+00])
# Attempt to include pumping constraints via strategy: p[(0,1)] == max(0, f[(0,1)]-c[(0,1)]) %python import numpy as np from scipy.optimize import minimize n = 10 # n denotes the number of edges in the network. # Setup strategy: There are 20 variables in the optimization problem. # Since there are 10 edges, we have 10 pumping rates, and 10 flow rates. # The objective function consists of the sum of the pumping rates, # which we want to minimize. # The constraints are split into two groups: (1) bounds, and (2) constraints. # The maximum flow capacity and pumping capacity are enforced as "bounds". # Flow continuity conditions at each node are enforced as "constraints". # Define the objective function def objective(p): return sum(p[i] for i in range(10)) # Initial guess for the solution p0 = np.zeros(20) # Define maximum flow capacities, and setup as bounds c = {(0):7, (1):4, (2):4, (3):2, (4):4, (5):4, (6):2.5, (7):2.5, (8):5, (9):3} bnds = ((0,5), (0,5), (0,5), (0,5), (0,5), (0,5), (0,5), (0,5), (0,5), (0,5), (0,c[(0)]), (0,c[(1)]), (0,c[(2)]), (0,c[(3)]), (0,c[(4)]), (0,c[(5)]), (0,c[(6)]), (0,c[(7)]), (0,c[(8)]), (0,c[(9)]) ) # Define flow continuity constraints at the nodes cons = ({'type':'eq', 'fun': lambda x: x[10]-x[11]-x[12]}, {'type':'eq', 'fun': lambda x: x[11]-x[13]}, {'type':'eq', 'fun': lambda x: x[12]-x[15]}, {'type':'eq', 'fun': lambda x: x[13]-x[14]}, {'type':'eq', 'fun': lambda x: x[15]-x[16]-x[17]}, {'type':'eq', 'fun': lambda x: x[14]+x[16]-x[18]}, {'type':'eq', 'fun': lambda x: x[17]-x[19]}, {'type':'ineq', 'fun': lambda x: x[10]-6.0}, {'type':'eq', 'fun': lambda x: x[0] - max(0, x[10]-c[(0)]) }, {'type':'eq', 'fun': lambda x: x[1] - max(0, x[11]-c[(1)]) }, {'type':'eq', 'fun': lambda x: x[2] - max(0, x[12]-c[(2)]) }, {'type':'eq', 'fun': lambda x: x[3] - max(0, x[13]-c[(3)]) }, # {'type':'eq', 'fun': lambda x: x[4] - max(0, x[14]-c[(4)]) } # {'type':'eq', 'fun': lambda x: x[5] - max(0, x[15]-c[(5)]) }, # {'type':'eq', 'fun': lambda x: x[6] - max(0, x[16]-c[(6)]) }, # {'type':'eq', 'fun': lambda x: x[7] - max(0, x[17]-c[(7)]) }, # {'type':'eq', 'fun': lambda x: x[8] - max(0, x[18]-c[(8)]) }, # {'type':'eq', 'fun': lambda x: x[9] - max(0, x[19]-c[(9)]) } ) # Call "minimize" and get computed solution res = minimize(objective, p0, method='SLSQP', bounds=bnds, constraints=cons) print res
fun: 1.4675421338203707e-15 jac: array([ 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]) message: 'Optimization terminated successfully.' nfev: 23 nit: 1 njev: 1 status: 0 success: True x: array([ 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 1.46754213e-15, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 6.00000000e+00, 2.00000000e+00, 4.00000000e+00, 2.00000000e+00, 2.00000000e+00, 4.00000000e+00, 1.50000000e+00, 2.50000000e+00, 3.50000000e+00, 2.50000000e+00])
%python minimize??
File: /ext/sage/sage-8.1/local/lib/python2.7/site-packages/scipy/optimize/_minimize.py Source: def minimize(fun, x0, args=(), method=None, jac=None, hess=None, hessp=None, bounds=None, constraints=(), tol=None, callback=None, options=None): """Minimization of scalar function of one or more variables. 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. ``g_i(x)`` are the inequality constraints. ``h_j(x)`` are the equality constrains. Optionally, the lower and upper bounds for each element in x can also be specified using the `bounds` argument. Parameters ---------- fun : callable Objective function. x0 : ndarray Initial guess. args : tuple, optional Extra arguments passed to the objective function and its derivatives (Jacobian, Hessian). method : str or callable, optional Type of solver. Should be one of - 'Nelder-Mead' :ref:`(see here) <optimize.minimize-neldermead>` - 'Powell' :ref:`(see here) <optimize.minimize-powell>` - 'CG' :ref:`(see here) <optimize.minimize-cg>` - 'BFGS' :ref:`(see here) <optimize.minimize-bfgs>` - 'Newton-CG' :ref:`(see here) <optimize.minimize-newtoncg>` - 'L-BFGS-B' :ref:`(see here) <optimize.minimize-lbfgsb>` - 'TNC' :ref:`(see here) <optimize.minimize-tnc>` - 'COBYLA' :ref:`(see here) <optimize.minimize-cobyla>` - 'SLSQP' :ref:`(see here) <optimize.minimize-slsqp>` - 'dogleg' :ref:`(see here) <optimize.minimize-dogleg>` - 'trust-ncg' :ref:`(see here) <optimize.minimize-trustncg>` - custom - a callable object (added in version 0.14.0), see below for description. If not given, chosen to be one of ``BFGS``, ``L-BFGS-B``, ``SLSQP``, depending if the problem has constraints or bounds. 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`. 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. bounds : sequence, optional Bounds for variables (only for L-BFGS-B, TNC and SLSQP). ``(min, max)`` pairs for each element in ``x``, defining the bounds on that parameter. Use None for one of ``min`` or ``max`` when there is no bound in that direction. constraints : dict or sequence of dict, optional Constraints definition (only for COBYLA and SLSQP). Each constraint is defined in a dictionary with fields: type : str Constraint type: 'eq' for equality, 'ineq' for inequality. fun : callable The function defining the constraint. jac : callable, optional The Jacobian of `fun` (only for SLSQP). args : sequence, optional Extra arguments to be passed to the function and Jacobian. Equality constraint means that the constraint function result is to be zero whereas inequality means that it is to be non-negative. Note that COBYLA only supports inequality constraints. tol : float, optional Tolerance for termination. For detailed control, use solver-specific options. options : dict, optional A dictionary of solver options. All methods accept the following generic options: maxiter : int Maximum number of iterations to perform. disp : bool Set to True to print convergence messages. For method-specific options, see :func:`show_options()`. callback : callable, optional Called after each iteration, as ``callback(xk)``, where ``xk`` is the current parameter vector. 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 and ``message`` which describes the cause of the termination. See `OptimizeResult` for a description of other attributes. See also -------- minimize_scalar : Interface to minimization algorithms for scalar univariate functions 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 *BFGS*. **Unconstrained minimization** Method :ref:`Nelder-Mead <optimize.minimize-neldermead>` uses the Simplex algorithm [1]_, [2]_. This algorithm is robust in many applications. However, if numerical computation of derivative can be trusted, other algorithms using the first and/or second derivatives information might be preferred for their better performance in general. Method :ref:`Powell <optimize.minimize-powell>` is a modification of Powell's method [3]_, [4]_ which is a conjugate direction method. It performs sequential one-dimensional minimizations along each vector of the directions set (`direc` field in `options` and `info`), which is updated at each iteration of the main minimization loop. The function need not be differentiable, and no derivatives are taken. Method :ref:`CG <optimize.minimize-cg>` uses a nonlinear conjugate gradient algorithm by Polak and Ribiere, a variant of the Fletcher-Reeves method described in [5]_ pp. 120-122. Only the first derivatives are used. Method :ref:`BFGS <optimize.minimize-bfgs>` uses the quasi-Newton method of Broyden, Fletcher, Goldfarb, and Shanno (BFGS) [5]_ pp. 136. It uses the first derivatives only. BFGS has proven good performance even for non-smooth optimizations. This method also returns an approximation of the Hessian inverse, stored as `hess_inv` in the OptimizeResult object. Method :ref:`Newton-CG <optimize.minimize-newtoncg>` uses a Newton-CG algorithm [5]_ pp. 168 (also known as the truncated Newton method). It uses a CG method to the compute the search direction. See also *TNC* method for a box-constrained minimization with a similar algorithm. Method :ref:`dogleg <optimize.minimize-dogleg>` uses the dog-leg trust-region algorithm [5]_ for unconstrained minimization. This algorithm requires the gradient and Hessian; furthermore the Hessian is required to be positive definite. Method :ref:`trust-ncg <optimize.minimize-trustncg>` uses the Newton conjugate gradient trust-region algorithm [5]_ for unconstrained minimization. This algorithm requires the gradient and either the Hessian or a function that computes the product of the Hessian with a given vector. **Constrained minimization** Method :ref:`L-BFGS-B <optimize.minimize-lbfgsb>` uses the L-BFGS-B algorithm [6]_, [7]_ for bound constrained minimization. Method :ref:`TNC <optimize.minimize-tnc>` uses a truncated Newton algorithm [5]_, [8]_ to minimize a function with variables subject to bounds. This algorithm uses gradient information; it is also called Newton Conjugate-Gradient. It differs from the *Newton-CG* method described above as it wraps a C implementation and allows each variable to be given upper and lower bounds. Method :ref:`COBYLA <optimize.minimize-cobyla>` uses the Constrained Optimization BY Linear Approximation (COBYLA) method [9]_, [10]_, [11]_. The algorithm is based on linear approximations to the objective function and each constraint. The method wraps a FORTRAN implementation of the algorithm. The constraints functions 'fun' may return either a single number or an array or list of numbers. Method :ref:`SLSQP <optimize.minimize-slsqp>` uses Sequential Least SQuares Programming to minimize a function of several variables with any combination of bounds, equality and inequality constraints. The method wraps the SLSQP Optimization subroutine originally implemented by Dieter Kraft [12]_. Note that the wrapper handles infinite values in bounds by converting them into large floating values. **Custom minimizers** It may be useful to pass a custom minimization method, for example when using a frontend to this method such as `scipy.optimize.basinhopping` or a different library. You can simply pass a callable as the ``method`` parameter. The callable is called as ``method(fun, x0, args, **kwargs, **options)`` where ``kwargs`` corresponds to any other parameters passed to `minimize` (such as `callback`, `hess`, etc.), except the `options` dict, which has its contents also passed as `method` parameters pair by pair. Also, if `jac` has been passed as a bool type, `jac` and `fun` are mangled so that `fun` returns just the function values and `jac` is converted to a function returning the Jacobian. The method shall return an ``OptimizeResult`` object. The provided `method` callable must be able to accept (and possibly ignore) arbitrary parameters; the set of parameters accepted by `minimize` may expand in future versions and then these parameters will be passed to the method. You can find an example in the scipy.optimize tutorial. .. versionadded:: 0.11.0 References ---------- .. [1] Nelder, J A, and R Mead. 1965. A Simplex Method for Function Minimization. The Computer Journal 7: 308-13. .. [2] Wright M H. 1996. Direct search methods: Once scorned, now respectable, in Numerical Analysis 1995: Proceedings of the 1995 Dundee Biennial Conference in Numerical Analysis (Eds. D F Griffiths and G A Watson). Addison Wesley Longman, Harlow, UK. 191-208. .. [3] Powell, M J D. 1964. An efficient method for finding the minimum of a function of several variables without calculating derivatives. The Computer Journal 7: 155-162. .. [4] Press W, S A Teukolsky, W T Vetterling and B P Flannery. Numerical Recipes (any edition), Cambridge University Press. .. [5] Nocedal, J, and S J Wright. 2006. Numerical Optimization. Springer New York. .. [6] Byrd, R H and P Lu and J. Nocedal. 1995. A Limited Memory Algorithm for Bound Constrained Optimization. SIAM Journal on Scientific and Statistical Computing 16 (5): 1190-1208. .. [7] Zhu, C and R H Byrd and J Nocedal. 1997. L-BFGS-B: Algorithm 778: L-BFGS-B, FORTRAN routines for large scale bound constrained optimization. ACM Transactions on Mathematical Software 23 (4): 550-560. .. [8] Nash, S G. Newton-Type Minimization Via the Lanczos Method. 1984. SIAM Journal of Numerical Analysis 21: 770-778. .. [9] Powell, M J D. A direct search optimization method that models the objective and constraint functions by linear interpolation. 1994. Advances in Optimization and Numerical Analysis, eds. S. Gomez and J-P Hennart, Kluwer Academic (Dordrecht), 51-67. .. [10] Powell M J D. Direct search algorithms for optimization calculations. 1998. Acta Numerica 7: 287-336. .. [11] Powell M J D. A view of algorithms for optimization without derivatives. 2007.Cambridge University Technical Report DAMTP 2007/NA03 .. [12] Kraft, D. A software package for sequential quadratic programming. 1988. Tech. Rep. DFVLR-FB 88-28, DLR German Aerospace Center -- Institute for Flight Mechanics, Koln, Germany. Examples -------- Let us consider the problem of minimizing the Rosenbrock function. This function (and its respective derivatives) is implemented in `rosen` (resp. `rosen_der`, `rosen_hess`) in the `scipy.optimize`. >>> from scipy.optimize import minimize, rosen, rosen_der A simple application of the *Nelder-Mead* method is: >>> x0 = [1.3, 0.7, 0.8, 1.9, 1.2] >>> res = minimize(rosen, x0, method='Nelder-Mead', tol=1e-6) >>> res.x array([ 1., 1., 1., 1., 1.]) Now using the *BFGS* algorithm, using the first derivative and a few options: >>> res = minimize(rosen, x0, method='BFGS', jac=rosen_der, ... options={'gtol': 1e-6, 'disp': True}) Optimization terminated successfully. Current function value: 0.000000 Iterations: 26 Function evaluations: 31 Gradient evaluations: 31 >>> res.x array([ 1., 1., 1., 1., 1.]) >>> print(res.message) Optimization terminated successfully. >>> res.hess_inv array([[ 0.00749589, 0.01255155, 0.02396251, 0.04750988, 0.09495377], # may vary [ 0.01255155, 0.02510441, 0.04794055, 0.09502834, 0.18996269], [ 0.02396251, 0.04794055, 0.09631614, 0.19092151, 0.38165151], [ 0.04750988, 0.09502834, 0.19092151, 0.38341252, 0.7664427 ], [ 0.09495377, 0.18996269, 0.38165151, 0.7664427, 1.53713523]]) Next, consider a minimization problem with several constraints (namely Example 16.4 from [5]_). The objective function is: >>> fun = lambda x: (x[0] - 1)**2 + (x[1] - 2.5)**2 There are three constraints defined as: >>> cons = ({'type': 'ineq', 'fun': lambda x: x[0] - 2 * x[1] + 2}, ... {'type': 'ineq', 'fun': lambda x: -x[0] - 2 * x[1] + 6}, ... {'type': 'ineq', 'fun': lambda x: -x[0] + 2 * x[1] + 2}) And variables must be positive, hence the following bounds: >>> bnds = ((0, None), (0, None)) The optimization problem is solved using the SLSQP method as: >>> res = minimize(fun, (2, 0), method='SLSQP', bounds=bnds, ... constraints=cons) It should converge to the theoretical solution (1.4 ,1.7). """ x0 = np.asarray(x0) if x0.dtype.kind in np.typecodes["AllInteger"]: x0 = np.asarray(x0, dtype=float) if not isinstance(args, tuple): args = (args,) if method is None: # Select automatically if constraints: method = 'SLSQP' elif bounds is not None: method = 'L-BFGS-B' else: method = 'BFGS' if callable(method): meth = "_custom" else: meth = method.lower() if options is None: options = {} # check if optional parameters are supported by the selected method # - jac if meth in ['nelder-mead', 'powell', 'cobyla'] and bool(jac): warn('Method %s does not use gradient information (jac).' % method, RuntimeWarning) # - hess if meth not in ('newton-cg', 'dogleg', 'trust-ncg', '_custom') and hess is not None: warn('Method %s does not use Hessian information (hess).' % method, RuntimeWarning) # - hessp if meth not in ('newton-cg', 'dogleg', 'trust-ncg', '_custom') and hessp is not None: warn('Method %s does not use Hessian-vector product ' 'information (hessp).' % method, RuntimeWarning) # - constraints or bounds if (meth in ['nelder-mead', 'powell', 'cg', 'bfgs', 'newton-cg', 'dogleg', 'trust-ncg'] and (bounds is not None or np.any(constraints))): warn('Method %s cannot handle constraints nor bounds.' % method, RuntimeWarning) if meth in ['l-bfgs-b', 'tnc'] and np.any(constraints): warn('Method %s cannot handle constraints.' % method, RuntimeWarning) if meth == 'cobyla' and bounds is not None: warn('Method %s cannot handle bounds.' % method, RuntimeWarning) # - callback if (meth in ['cobyla'] and callback is not None): warn('Method %s does not support callback.' % method, RuntimeWarning) # - return_all if (meth in ['l-bfgs-b', 'tnc', 'cobyla', 'slsqp'] and options.get('return_all', False)): warn('Method %s does not support the return_all option.' % method, RuntimeWarning) # fun also returns the jacobian if not callable(jac): 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 == 'nelder-mead': options.setdefault('xatol', tol) options.setdefault('fatol', tol) if meth in ['newton-cg', 'powell', 'tnc']: options.setdefault('xtol', tol) if meth in ['powell', 'l-bfgs-b', 'tnc', 'slsqp']: options.setdefault('ftol', tol) if meth in ['bfgs', 'cg', 'l-bfgs-b', 'tnc', 'dogleg', 'trust-ncg']: options.setdefault('gtol', tol) if meth in ['cobyla', '_custom']: options.setdefault('tol', tol) if meth == '_custom': return method(fun, x0, args=args, jac=jac, hess=hess, hessp=hessp, bounds=bounds, constraints=constraints, callback=callback, **options) elif meth == 'nelder-mead': return _minimize_neldermead(fun, x0, args, callback, **options) elif meth == 'powell': return _minimize_powell(fun, x0, args, callback, **options) elif meth == 'cg': return _minimize_cg(fun, x0, args, jac, callback, **options) elif meth == 'bfgs': return _minimize_bfgs(fun, x0, args, jac, callback, **options) elif meth == 'newton-cg': return _minimize_newtoncg(fun, x0, args, jac, hess, hessp, callback, **options) elif meth == 'l-bfgs-b': return _minimize_lbfgsb(fun, x0, args, jac, bounds, callback=callback, **options) elif meth == 'tnc': return _minimize_tnc(fun, x0, args, jac, bounds, callback=callback, **options) elif meth == 'cobyla': return _minimize_cobyla(fun, x0, args, constraints, **options) elif meth == 'slsqp': return _minimize_slsqp(fun, x0, args, jac, bounds, constraints, callback=callback, **options) elif meth == 'dogleg': return _minimize_dogleg(fun, x0, args, jac, hess, callback=callback, **options) elif meth == 'trust-ncg': return _minimize_trust_ncg(fun, x0, args, jac, hess, hessp, callback=callback, **options) else: raise ValueError('Unknown solver %s' % method)