U
    Ä@·f!H  ã                   @   sŽ   d Z ddlZddlmZ dgZdddd	d
dddgZG dd„ dƒZd"dd„Z	dd„ Z
dd„ Zdd„ Zdd„ Zdd„ Zdd„ Zdd„ Zd d!„ ZdS )#z•
Unified interfaces to root finding algorithms for real or complex
scalar functions.

Functions
---------
- root : find a root of a scalar function.
é    Né   )Ú	_zeros_pyÚroot_scalarÚbisectÚbrentqÚbrenthÚridderÚtoms748ÚnewtonÚsecantÚhalleyc                   @   s8   e Zd ZdZdd„ Zdd„ Zdd„ Zdd	„ Zd
d„ ZdS )Ú
MemoizeDeraš  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.c                 C   s   || _ d | _d | _d| _d S )Nr   )ÚfunÚvalsÚxÚn_calls)Úselfr   © r   ú?/tmp/pip-unpacked-wheel-w7avvj8p/scipy/optimize/_root_scalar.pyÚ__init__   s    zMemoizeDer.__init__c                 G   sP   | j dks|| jkrF| j|f|žŽ }|| _|  jd7  _|dd… | _ | j d S )z,Calculate f or use cached value if availableNr   r   )r   r   r   r   )r   r   ÚargsZfgr   r   r   Ú__call__#   s    zMemoizeDer.__call__c                 G   s,   | j dks|| jkr"| |f|žŽ  | j d S )z/Calculate f' or use a cached value if availableNr   ©r   r   ©r   r   r   r   r   r   Úfprime-   s    zMemoizeDer.fprimec                 G   s,   | j dks|| jkr"| |f|žŽ  | j d S )z0Calculate f'' or use a cached value if availableNé   r   r   r   r   r   Úfprime23   s    zMemoizeDer.fprime2c                 C   s   | j S )N)r   )r   r   r   r   Úncalls9   s    zMemoizeDer.ncallsN)	Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r   r   r   r   r   r   r   r   r      s   	
r   r   c              
   C   s6  t |tƒs|f}|dkri }d}|dk	rVt|ƒsVt|ƒrRt| ƒ} d}| j}| j}nd}|dk	r†t|ƒs†t|ƒr‚t| ƒ} d}| j}nd}i }dD ] }tƒ  |¡}|dk	rŽ|||< qŽ|r¾| 	|¡ |j	ddd |sú|rÚd}n |dk	rú|rö|rðd}qúd}nd	}|st
d
ƒ‚| ¡ }dddœ}ztt| ||¡ƒ}W n2 tk
rb } zt
d| ƒ|‚W 5 d}~X Y nX |dkr¾t |tttjfƒsŽt
d| ƒ‚|dd… \}}|| ||fd|i|—Ž\}}nb|dkr.|dkrÞt
d| ƒ‚|dkrôt
d| ƒ‚d|kr| d¡|d< || |f|dd|dœ|—Ž\}}nò|dkr˜|dkrNt
d| ƒ‚|s`t
d| ƒ‚d|krx| d¡|d< || |f||ddœ|—Ž\}}nˆ|dkr|dkr¸t
d| ƒ‚|sÊt
d| ƒ‚|sÜt
d| ƒ‚d|krô| d¡|d< || |f|||dœ|—Ž\}}nt
d| ƒ‚|r2| j}||_|S )aV  
    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) <optimize.root_scalar-bisect>`
            - 'brentq'    :ref:`(see here) <optimize.root_scalar-brentq>`
            - 'brenth'    :ref:`(see here) <optimize.root_scalar-brenth>`
            - 'ridder'    :ref:`(see here) <optimize.root_scalar-ridder>`
            - 'toms748'    :ref:`(see here) <optimize.root_scalar-toms748>`
            - 'newton'    :ref:`(see here) <optimize.root_scalar-newton>`
            - 'secant'    :ref:`(see here) <optimize.root_scalar-secant>`
            - 'halley'    :ref:`(see here) <optimize.root_scalar-halley>`

    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 <optimize.root_scalar-bisect>`   | x |  o   |    x    |    |    |        |         |  o   |  o   |    o    |   o     |
    +-----------------------------------------------+---+------+---------+----+----+--------+---------+------+------+---------+---------+
    | :ref:`brentq <optimize.root_scalar-brentq>`   | x |  o   |    x    |    |    |        |         |  o   |  o   |    o    |   o     |
    +-----------------------------------------------+---+------+---------+----+----+--------+---------+------+------+---------+---------+
    | :ref:`brenth <optimize.root_scalar-brenth>`   | x |  o   |    x    |    |    |        |         |  o   |  o   |    o    |   o     |
    +-----------------------------------------------+---+------+---------+----+----+--------+---------+------+------+---------+---------+
    | :ref:`ridder <optimize.root_scalar-ridder>`   | x |  o   |    x    |    |    |        |         |  o   |  o   |    o    |   o     |
    +-----------------------------------------------+---+------+---------+----+----+--------+---------+------+------+---------+---------+
    | :ref:`toms748 <optimize.root_scalar-toms748>` | x |  o   |    x    |    |    |        |         |  o   |  o   |    o    |   o     |
    +-----------------------------------------------+---+------+---------+----+----+--------+---------+------+------+---------+---------+
    | :ref:`newton <optimize.root_scalar-newton>`   | x |  o   |         | x  |    |   x    |         |  o   |  o   |    o    |   o     |
    +-----------------------------------------------+---+------+---------+----+----+--------+---------+------+------+---------+---------+
    | :ref:`secant <optimize.root_scalar-secant>`   | x |  o   |         | x  | x  |        |         |  o   |  o   |    o    |   o     |
    +-----------------------------------------------+---+------+---------+----+----+--------+---------+------+------+---------+---------+
    | :ref:`halley <optimize.root_scalar-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)


    NFT)ÚxtolÚrtolÚmaxiter)Zfull_outputZdispr   r   r
   r   zIUnable to select a solver as neither bracket nor starting point provided.)r   r   zUnknown solver %s)r   r   r   r   r	   zBracket needed for %sr   r   )r   zx0 must not be None for %szx1 must not be None for %sr"   Ztol)r   r   r   Úx1)r
   zfprime must be specified for %s)r   r   r   )r   z fprime2 must be specified for %s)Ú
isinstanceÚtupleÚcallableÚboolr   r   r   ÚlocalsÚgetÚupdateÚ
ValueErrorÚlowerÚgetattrÚoptzerosÚAttributeErrorÚlistÚnpZndarrayÚpopr   Zfunction_calls)Úfr   ÚmethodZbracketr   r   Zx0r%   r"   r#   r$   ÚoptionsZis_memoizedÚkwargsÚkÚvÚmethZmap2underlyingZmethodcÚeÚaÚbÚrZsolr   r   r   r   r   =   s¬     



 
 



ÿÿ


ÿ


 c                   C   s   dS )a?  
    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

    Nr   r   r   r   r   Ú_root_scalar_brentq_doc<  s    r@   c                   C   s   dS ©a@  
    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.

    Nr   r   r   r   r   Ú_root_scalar_brenth_docR  s    rB   c                   C   s   dS rA   r   r   r   r   r   Ú_root_scalar_toms748_docg  s    rC   c                   C   s   dS )a  
    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.

    Nr   r   r   r   r   Ú_root_scalar_secant_doc}  s    rD   c                   C   s   dS )a"  
    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.

    Nr   r   r   r   r   Ú_root_scalar_newton_doc”  s    rE   c                   C   s   dS )ar  
    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.

    Nr   r   r   r   r   Ú_root_scalar_halley_doc®  s    rF   c                   C   s   dS rA   r   r   r   r   r   Ú_root_scalar_ridder_docÍ  s    rG   c                   C   s   dS rA   r   r   r   r   r   Ú_root_scalar_bisect_docã  s    rH   )r   NNNNNNNNNN)r!   Znumpyr3   Ú r   r0   Ú__all__ZROOT_SCALAR_METHODSr   r   r@   rB   rC   rD   rE   rF   rG   rH   r   r   r   r   Ú<module>   s:   
  ÿ*             ü
  