def fsolve(func, x0, args=(), fprime=None, full_output=0, col_deriv=0, xtol=1.49012e-8, maxfev=0, band=None, epsfcn=0.0, factor=100, diag=None, warning=True): """Find the roots of a function. Description: Return the roots of the (non-linear) equations defined by func(x)=0 given a starting estimate. Inputs: func -- A Python function or method which takes at least one (possibly vector) argument. x0 -- The starting estimate for the roots of func(x)=0. args -- Any extra arguments to func are placed in this tuple. fprime -- 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 -- non-zero to return the optional outputs. col_deriv -- non-zero to specify that the Jacobian function computes derivatives down the columns (faster, because there is no transpose operation). warning -- True to print a warning message when the call is unsuccessful; False to suppress the warning message. Outputs: (x, {infodict, ier, mesg}) x -- the solution (or the result of the last iteration for an unsuccessful call. infodict -- a dictionary of optional outputs with the keys: 'nfev' : the number of function calls 'njev' : the number of jacobian calls 'fvec' : the 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 same matrix. 'qtf' : the vector (transpose(q) * fvec). ier -- an integer flag. If it is equal to 1 the solution was found. If it is not equal to 1, the solution was not found and the following message gives more information. mesg -- a string message giving information about the cause of failure. Extended Inputs: xtol -- The calculation will terminate if the relative error between two consecutive iterates is at most xtol. maxfev -- 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 -- If set to a two-sequence containing the number of sub- and superdiagonals within the band of the Jacobi matrix, the Jacobi matrix is considered banded (only for fprime=None). epsfcn -- 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 -- A parameter determining the initial step bound (factor * || diag * x||). Should be in interval (0.1,100). diag -- A sequency of N positive entries that serve as a scale factors for the variables. Remarks: "fsolve" is a wrapper around MINPACK's hybrd and hybrj algorithms. See also: scikits.openopt, which offers a unified syntax to call this and other solvers fmin, fmin_powell, fmin_cg, fmin_bfgs, fmin_ncg -- multivariate local optimizers leastsq -- nonlinear least squares minimizer fmin_l_bfgs_b, fmin_tnc, fmin_cobyla -- constrained multivariate optimizers anneal, brute -- global optimizers fminbound, brent, golden, bracket -- local scalar minimizers brentq, brenth, ridder, bisect, newton -- one-dimensional root-finding fixed_point -- scalar and vector fixed-point finder """ x0 = array(x0, ndmin=1) n = len(x0) if type(args) != type(()): args = (args, ) check_func(func, x0, args, n, (n, )) Dfun = fprime 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, full_output, xtol, maxfev, ml, mu, epsfcn, factor, diag) else: check_func(Dfun, x0, args, n, (n, n)) if (maxfev == 0): maxfev = 100 * (n + 1) retval = _minpack._hybrj(func, Dfun, x0, args, full_output, col_deriv, xtol, maxfev, factor, diag) errors = { 0: ["Improper input parameters were entered.", TypeError], 1: ["The solution converged.", None], 2: [ "The number of calls to function has reached maxfev = %d." % maxfev, ValueError ], 3: [ "xtol=%f is too small, no further improvement in the approximate\n solution is possible." % xtol, ValueError ], 4: [ "The iteration is not making good progress, as measured by the \n improvement from the last five Jacobian evaluations.", ValueError ], 5: [ "The iteration is not making good progress, as measured by the \n improvement from the last ten iterations.", ValueError ], 'unknown': ["An error occurred.", TypeError] } info = retval[-1] # The FORTRAN return value if (info != 1 and not full_output): if info in [2, 3, 4, 5]: if warning: print "Warning: " + errors[info][0] else: try: raise errors[info][1], errors[info][0] except KeyError: raise errors['unknown'][1], errors['unknown'][0] if n == 1: retval = (retval[0][0], ) + retval[1:] if full_output: try: return retval + (errors[info][0], ) # Return all + the message except KeyError: return retval + (errors['unknown'][0], ) else: return retval[0]
def fsolve(func, x0, args=(), fprime=None, full_output=0, col_deriv=0, xtol=1.49012e-8, maxfev=0, band=None, epsfcn=0.0, 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. x0 : ndarray The starting estimate for the roots of ``func(x) = 0``. args : tuple Any extra arguments to `func`. fprime : callable(x) A function to compute the Jacobian of `func` with derivatives across the rows. By default, the Jacobian will be estimated. full_output : bool If True, return optional outputs. col_deriv : bool Specify whether the Jacobian function computes derivatives down the columns (faster, because there is no transpose operation). 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 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. Other Parameters ---------------- 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``). epsfcn : float 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 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. Notes ----- ``fsolve`` is a wrapper around MINPACK's hybrd and hybrj algorithms. """ x0 = array(x0, ndmin=1) n = len(x0) if type(args) != type(()): args = (args,) _check_func('fsolve', 'func', func, x0, args, n, (n,)) Dfun = fprime 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, full_output, 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, full_output, col_deriv, xtol, maxfev, factor,diag) errors = {0:["Improper input parameters were entered.",TypeError], 1:["The solution converged.", None], 2:["The number of calls to function has " "reached maxfev = %d." % maxfev, ValueError], 3:["xtol=%f is too small, no further improvement " "in the approximate\n solution " "is possible." % xtol, ValueError], 4:["The iteration is not making good progress, as measured " "by the \n improvement from the last five " "Jacobian evaluations.", ValueError], 5:["The iteration is not making good progress, " "as measured by the \n improvement from the last " "ten iterations.", ValueError], 'unknown': ["An error occurred.", TypeError]} info = retval[-1] # The FORTRAN return value if (info != 1 and not full_output): if info in [2,3,4,5]: msg = errors[info][0] warnings.warn(msg, RuntimeWarning) else: try: raise errors[info][1](errors[info][0]) except KeyError: raise errors['unknown'][1](errors['unknown'][0]) if full_output: try: return retval + (errors[info][0],) # Return all + the message except KeyError: return retval + (errors['unknown'][0],) else: return retval[0]
def fsolve(func, x0, args=(), fprime=None, full_output=0, col_deriv=0, xtol=1.49012e-8, maxfev=0, band=None, epsfcn=0.0, factor=100, diag=None, warning=True): """ 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. x0 : ndarray The starting estimate for the roots of ``func(x) = 0``. args : tuple Any extra arguments to `func`. fprime : callable(x) A function to compute the Jacobian of `func` with derivatives across the rows. By default, the Jacobian will be estimated. full_output : bool If True, return optional outputs. col_deriv : bool Specify whether the Jacobian function computes derivatives down the columns (faster, because there is no transpose operation). warning : bool Whether to print a warning message when the call is unsuccessful. This option is deprecated, use the warnings module instead. 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 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. Other Parameters ---------------- 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``). epsfcn : float 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 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. Notes ----- ``fsolve`` is a wrapper around MINPACK's hybrd and hybrj algorithms. From scipy 0.8.0 `fsolve` returns an array of size one instead of a scalar when solving for a single parameter. """ if not warning: msg = "The warning keyword is deprecated. Use the warnings module." warnings.warn(msg, DeprecationWarning) x0 = array(x0, ndmin=1) n = len(x0) if type(args) != type(()): args = (args, ) check_func(func, x0, args, n, (n, )) Dfun = fprime 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, full_output, xtol, maxfev, ml, mu, epsfcn, factor, diag) else: check_func(Dfun, x0, args, n, (n, n)) if (maxfev == 0): maxfev = 100 * (n + 1) retval = _minpack._hybrj(func, Dfun, x0, args, full_output, col_deriv, xtol, maxfev, factor, diag) errors = { 0: ["Improper input parameters were entered.", TypeError], 1: ["The solution converged.", None], 2: [ "The number of calls to function has " "reached maxfev = %d." % maxfev, ValueError ], 3: [ "xtol=%f is too small, no further improvement " "in the approximate\n solution " "is possible." % xtol, ValueError ], 4: [ "The iteration is not making good progress, as measured " "by the \n improvement from the last five " "Jacobian evaluations.", ValueError ], 5: [ "The iteration is not making good progress, " "as measured by the \n improvement from the last " "ten iterations.", ValueError ], 'unknown': ["An error occurred.", TypeError] } info = retval[-1] # The FORTRAN return value if (info != 1 and not full_output): if info in [2, 3, 4, 5]: msg = errors[info][0] warnings.warn(msg, RuntimeWarning) else: try: raise errors[info][1](errors[info][0]) except KeyError: raise errors['unknown'][1](errors['unknown'][0]) if full_output: try: return retval + (errors[info][0], ) # Return all + the message except KeyError: return retval + (errors['unknown'][0], ) else: return retval[0]
def _root_hybr(func, x0, args=(), jac=None, col_deriv=0, xtol=1.49012e-08, maxfev=0, band=None, eps=0.0, factor=100, diag=None, full_output=0, **unknown_options): """ Find the roots of a multivariate function using MINPACK's hybrd and hybrj routines (modified Powell method). Options for the hybrd algorithm are: 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. This function is called by the `root` function with `method=hybr`. It is not supposed to be called directly. """ _check_unknown_options(unknown_options) epsfcn = eps x0 = array(x0, ndmin=1) n = len(x0) if type(args) != type(()): args = (args,) _check_func('fsolve', 'func', func, x0, args, n, (n,)) 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.",TypeError], 1:["The solution converged.", None], 2:["The number of calls to function has " "reached maxfev = %d." % maxfev, ValueError], 3:["xtol=%f is too small, no further improvement " "in the approximate\n solution " "is possible." % xtol, ValueError], 4:["The iteration is not making good progress, as measured " "by the \n improvement from the last five " "Jacobian evaluations.", ValueError], 5:["The iteration is not making good progress, " "as measured by the \n improvement from the last " "ten iterations.", ValueError], 'unknown': ["An error occurred.", TypeError]} if status != 1 and not full_output: if status in [2,3,4,5]: msg = errors[status][0] warnings.warn(msg, RuntimeWarning) else: try: raise errors[status][1](errors[status][0]) except KeyError: raise errors['unknown'][1](errors['unknown'][0]) info = retval[1] info['fun'] = info.pop('fvec') sol = Result(x=x, success=(status==1), status=status) sol.update(info) try: sol['message'] = errors[status][0] except KeyError: info['message'] = errors['unknown'][0] return sol
def fsolve(func,x0,args=(),fprime=None,full_output=0,col_deriv=0,xtol=1.49012e-8,maxfev=0,band=None,epsfcn=0.0,factor=100,diag=None, warning=True): """ 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 A Python function or method which takes at least one (possibly vector) argument. x0 The starting estimate for the roots of func(x)=0. args Any extra arguments to func are placed in this tuple. fprime 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 Non-zero to return the optional outputs. col_deriv Non-zero to specify that the Jacobian function computes derivatives down the columns (faster, because there is no transpose operation). warning True to print a warning message when the call is unsuccessful; False to suppress the warning message. Returns ------- x The solution (or the result of the last iteration for an unsuccessful call. infodict 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 same matrix * 'qtf': the vector (transpose(q) * fvec) ier An integer flag. If it is 1, the solution was found. If it is 1, the solution was not found and the following message gives more information. mesg A string message giving information about the cause of failure. Other Parameters ---------------- xtol The calculation will terminate if the relative error between two consecutive iterates is at most `xtol`. maxfev 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 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 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 A parameter determining the initial step bound (`factor` * || `diag` * x||). Should be in the interval (0.1,100). diag A sequency of N positive entries that serve as a scale factors for the variables. Notes ----- "fsolve" is a wrapper around MINPACK's hybrd and hybrj algorithms. See Also -------- scikits.openopt : offers a unified syntax to call this and other solvers fmin, fmin_powell, fmin_cg, fmin_bfgs, fmin_ncg : multivariate local optimizers leastsq : nonlinear least squares minimizer fmin_l_bfgs_b, fmin_tnc, fmin_cobyla : constrained multivariate optimizers anneal, brute : global optimizers fminbound, brent, golden, bracket : local scalar minimizers brentq, brenth, ridder, bisect, newton : one-dimensional root-finding fixed_point : scalar and vector fixed-point finder """ x0 = array(x0,ndmin=1) n = len(x0) if type(args) != type(()): args = (args,) check_func(func,x0,args,n,(n,)) Dfun = fprime 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,full_output,xtol,maxfev,ml,mu,epsfcn,factor,diag) else: check_func(Dfun,x0,args,n,(n,n)) if (maxfev == 0): maxfev = 100*(n+1) retval = _minpack._hybrj(func,Dfun,x0,args,full_output,col_deriv,xtol,maxfev,factor,diag) errors = {0:["Improper input parameters were entered.",TypeError], 1:["The solution converged.",None], 2:["The number of calls to function has reached maxfev = %d." % maxfev, ValueError], 3:["xtol=%f is too small, no further improvement in the approximate\n solution is possible." % xtol, ValueError], 4:["The iteration is not making good progress, as measured by the \n improvement from the last five Jacobian evaluations.", ValueError], 5:["The iteration is not making good progress, as measured by the \n improvement from the last ten iterations.", ValueError], 'unknown': ["An error occurred.", TypeError]} info = retval[-1] # The FORTRAN return value if (info != 1 and not full_output): if info in [2,3,4,5]: if warning: print "Warning: " + errors[info][0] else: try: raise errors[info][1], errors[info][0] except KeyError: raise errors['unknown'][1], errors['unknown'][0] if n == 1: retval = (retval[0][0],) + retval[1:] if full_output: try: return retval + (errors[info][0],) # Return all + the message except KeyError: return retval + (errors['unknown'][0],) else: return retval[0]
def _root_hybr(func, x0, args=(), jac=None, col_deriv=0, xtol=1.49012e-08, maxfev=0, band=None, eps=0.0, factor=100, diag=None, full_output=0, **unknown_options): """ Find the roots of a multivariate function using MINPACK's hybrd and hybrj routines (modified Powell method). Options for the hybrd algorithm are: 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. This function is called by the `root` function with `method=hybr`. It is not supposed to be called directly. """ _check_unknown_options(unknown_options) epsfcn = eps x0 = array(x0, ndmin=1) n = len(x0) if type(args) != type(()): args = (args, ) _check_func('fsolve', 'func', func, x0, args, n, (n, )) 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.", TypeError], 1: ["The solution converged.", None], 2: [ "The number of calls to function has " "reached maxfev = %d." % maxfev, ValueError ], 3: [ "xtol=%f is too small, no further improvement " "in the approximate\n solution " "is possible." % xtol, ValueError ], 4: [ "The iteration is not making good progress, as measured " "by the \n improvement from the last five " "Jacobian evaluations.", ValueError ], 5: [ "The iteration is not making good progress, " "as measured by the \n improvement from the last " "ten iterations.", ValueError ], 'unknown': ["An error occurred.", TypeError] } if status != 1 and not full_output: if status in [2, 3, 4, 5]: msg = errors[status][0] warnings.warn(msg, RuntimeWarning) else: try: raise errors[status][1](errors[status][0]) except KeyError: raise errors['unknown'][1](errors['unknown'][0]) info = retval[1] info['fun'] = info.pop('fvec') sol = Result(x=x, success=(status == 1), status=status) sol.update(info) try: sol['message'] = errors[status][0] except KeyError: info['message'] = errors['unknown'][0] return sol