"""
Optimization algorithms for Biogeme

:author: Michel Bierlaire
:date: Mon Dec 21 10:24:24 2020

"""

# There seems to be a bug in PyLint.
# pylint: disable=invalid-unary-operand-type, no-member

# Too constraining
# pylint: disable=invalid-name
# pylint: disable=too-many-lines, too-many-locals
# pylint: disable=too-many-arguments, too-many-branches
# pylint: disable=too-many-statements, too-many-return-statements
# pylint: disable=bare-except


import numpy as np
import scipy.optimize as sc
import biogeme.algorithms as alg
import biogeme.exceptions as excep
import biogeme.messaging as msg


logger = msg.bioMessage()


def scipy(fct, initBetas, bounds, parameters=None):

    """Optimization interface for Biogeme, based on the scipy 
    minimize function.

    :param fct: object to calculate the objective function and its derivatives.
    :type fct: algorithms.functionToMinimize

    :param initBetas: initial value of the beta parameters
    :type initBetas: numpy.array
    :param bounds: list of tuples (ell,u) containing the lower and upper bounds
          for each free parameter
    :type bounds: list(tuple)
    :param parameters: dict of parameters to be transmitted to the
         optimization routine. See the `scipy`_ documentation.

    .. _`scipy`: https://docs.scipy.org/doc/scipy/reference/optimize.html

    :type parameters: dict(string:float or string)

    :return: x, messages

        - x is the solution generated by the algorithm,
        - messages is a dictionary describing several information
          about the algorithm

    :rtype: numpay.array, dict(str:object)

    """

    def f_and_grad(x):
        fct.setVariables(x)
        f, g = fct.f_g()
        return f, g

    # Absolute tolerance
    absgtol = 1.0e-7
    opts = {'ftol': np.finfo(np.float64).eps, 'gtol': absgtol}
    if parameters is not None:
        opts = {**opts, **parameters}

    if 'gtol' in opts.keys():
        logger.general(f'Minimize with tol {opts["gtol"]}')

    results = sc.minimize(
        f_and_grad, initBetas, bounds=bounds, jac=True, options=opts
    )

    messages = {
        'Algorithm': 'scipy.optimize',
        'Cause of termination': results.message,
        'Number of iterations': results.nit,
        'Number of function evaluations': results.nfev,
    }

    return results.x, messages


def newtonLineSearchForBiogeme(fct, initBetas, bounds, parameters=None):
    """Optimization interface for Biogeme, based on Newton method.

    :param fct: object to calculate the objective function and its derivatives.
    :type fct: algorithms.functionToMinimize

    :param initBetas: initial value of the parameters.
    :type initBetas: numpy.array

    :param bounds: list of tuples (ell,u) containing the lower and
                   upper bounds for each free parameter. Note that
                   this algorithm does not support bound constraints.
                   Therefore, all the bounds must be None.

    :type bounds: list(tuples)

    :param parameters: dict of parameters to be transmitted to the
        optimization routine:

        - tolerance: when the relative gradient is below that
          threshold, the algorithm has reached convergence
          (default: :math:`\\varepsilon^{\\frac{1}{3}}`);
        - maxiter: the maximum number of iterations (default: 100).

    :type parameters: dict(string:float or int)

    :return: tuple x, nit, nfev, message, where

            - x is the solution found,
            - messages is a dictionary reporting various aspects
              related to the run of the algorithm.

    :rtype: numpy.array, dict(str:object)

    :raises biogeme.exceptions.biogemeError: if bounds are imposed on
                the variables.

    """
    for ell, u in bounds:
        if ell is not None or u is not None:
            errorMsg = (
                'This algorithm does not handle bound constraints. '
                'Remove the bounds, or select another algorithm.'
            )
            raise excep.biogemeError(errorMsg)

    tol = np.finfo(np.float64).eps ** 0.3333
    maxiter = 100
    if parameters is not None:
        if 'tolerance' in parameters:
            tol = parameters['tolerance']
        if 'maxiter' in parameters:
            maxiter = parameters['maxiter']

    logger.detailed('** Optimization: Newton with linesearch')
    return alg.newtonLineSearch(fct, initBetas, eps=tol, maxiter=maxiter)


def newtonTrustRegionForBiogeme(fct, initBetas, bounds, parameters=None):
    """Optimization interface for Biogeme, based on Newton method with TR.

    :param fct: object to calculate the objective function and its derivatives.
    :type fct: algorithms.functionToMinimize

    :param initBetas: initial value of the parameters.
    :type initBetas: numpy.array

    :param bounds: list of tuples (ell, u) containing the lower and
                   upper bounds for each free parameter. Note that
                   this algorithm does not support bound constraints.
                   Therefore, all the bounds must be None.
    :type bounds: list(tuples)

    :param parameters: dict of parameters to be transmitted to the
        optimization routine:

        - tolerance: when the relative gradient is below that threshold,
          the algorithm has reached convergence
          (default:  :math:`\\varepsilon^{\\frac{1}{3}}`);
        - maxiter: the maximum number of iterations (default: 100).
        - dogleg: if True, the trust region subproblem is solved using
          the Dogleg method. If False, it is solved using the
          truncated conjugate gradient method (default: False).
        - radius: the initial radius of the truat region (default: 1.0).

    :type parameters: dict(string:float or int)

    :return: tuple x, messages, where

            - x is the solution found,
            - messages is a dictionary reporting various aspects
              related to the run of the algorithm.

    :rtype: numpy.array, dict(str:object)

    :raises biogeme.exceptions.biogemeError: if bounds are imposed on
          the variables.

    """
    for ell, u in bounds:
        if ell is not None or u is not None:
            errorMsg = (
                'This algorithm does not handle bound constraints. '
                'Remove the bounds, or select another algorithm.'
            )
            raise excep.biogemeError(errorMsg)

    tol = np.finfo(np.float64).eps ** 0.3333
    maxiter = 100
    applyDogleg = False
    radius = 1.0
    if parameters is not None:
        if 'tolerance' in parameters:
            tol = parameters['tolerance']
        if 'maxiter' in parameters:
            maxiter = parameters['maxiter']
        if 'dogleg' in parameters:
            applyDogleg = parameters['dogleg']
        if 'radius' in parameters:
            radius = parameters['radius']

    logger.detailed('** Optimization: Newton with trust region')
    return alg.newtonTrustRegion(
        fct,
        x0=initBetas,
        delta0=radius,
        eps=tol,
        dl=applyDogleg,
        maxiter=maxiter,
    )


def bfgsLineSearchForBiogeme(fct, initBetas, bounds, parameters=None):
    """Optimization interface for Biogeme, based on BFGS
    quasi-Newton method with LS.

    :param fct: object to calculate the objective function and its derivatives.

    :type fct: algorithms.functionToMinimize

    :param initBetas: initial value of the parameters.

    :type initBetas: numpy.array

    :param bounds: list of tuples (ell,u) containing the lower and
                   upper bounds for each free parameter. Note that
                   this algorithm does not support bound constraints.
                   Therefore, all the bounds must be None.

    :type bounds: list(tuples)

    :param parameters: dict of parameters to be transmitted to the
        optimization routine:

        - tolerance: when the relative gradient is below that
          threshold, the algorithm has reached convergence
          (default: :math:`\\varepsilon^{\\frac{1}{3}}`);

        - maxiter: the maximum number of iterations (default: 100).

        - | initBfgs: the positive definite matrix that initalizes the
                      BFGS updates. If None, the identity matrix is
                      used. Default: None.


    :type parameters: dict(string:float or int)

    :return: tuple x, messages, where

            - x is the solution found,

            - messages is a dictionary reporting various aspects
              related to the run of the algorithm.

    :rtype: numpy.array, dict(str:object)

    :raises biogeme.exceptions.biogemeError: if bounds are imposed on
                                             the variables.

    """
    for ell, u in bounds:
        if ell is not None or u is not None:
            errorMsg = (
                'This algorithm does not handle bound constraints. '
                'Remove the bounds, or select another algorithm.'
            )
            raise excep.biogemeError(errorMsg)

    tol = np.finfo(np.float64).eps ** 0.3333
    maxiter = 100
    initBfgs = None
    if parameters is not None:
        if 'tolerance' in parameters:
            tol = parameters['tolerance']
            if 'maxiter' in parameters:
                maxiter = parameters['maxiter']
            if 'initBfgs' in parameters:
                initBfgs = parameters['initBfgs']

    logger.detailed('** Optimization: BFGS with line search')
    return alg.bfgsLineSearch(
        fct, x0=initBetas, initBfgs=initBfgs, eps=tol, maxiter=maxiter
    )


def bfgsTrustRegionForBiogeme(fct, initBetas, bounds, parameters=None):
    """Optimization interface for Biogeme, based on Newton method with TR.

    :param fct: object to calculate the objective function and its derivatives.
    :type fct: algorithms.functionToMinimize

    :param initBetas: initial value of the parameters.
    :type initBetas: numpy.array

    :param bounds: list of tuples (ell,u) containing the lower and
                   upper bounds for each free parameter. Note that
                   this algorithm does not support bound constraints.
                   Therefore, all the bounds must be None.
    :type bounds: list(tuples)

    :param parameters: dict of parameters to be transmitted to the
         optimization routine:

         - tolerance: when the relative gradient is below that
           threshold, the algorithm has reached convergence
           (default: :math:`\\varepsilon^{\\frac{1}{3}}`);

         - maxiter: the maximum number of iterations (default: 100).

         - dogleg: if True, the trust region subproblem is solved using
           the Dogleg method. If False, it is solved using the
           truncated conjugate gradient method (default: False).

         - radius: the initial radius of the truat region (default: 1.0).

         - initBfgs: the positive definite matrix that initalizes the
           BFGS updates. If None, the identity matrix is
           used. Default: None.


    :type parameters: dict(string:float or int)

    :return: tuple x, messages, where

            - x is the solution found,
            - messages is a dictionary reporting various aspects
              related to the run of the algorithm.
    :rtype: numpy.array, dict(str:object)

    :raises biogeme.exceptions.biogemeError: if bounds are imposed on
            the variables.

    """
    for ell, u in bounds:
        if ell is not None or u is not None:
            errorMsg = (
                'This algorithm does not handle bound constraints. '
                'Remove the bounds, or select another algorithm.'
            )
            raise excep.biogemeError(errorMsg)

    tol = np.finfo(np.float64).eps ** 0.3333
    maxiter = 100
    applyDogleg = False
    radius = 1.0
    initBfgs = None
    if parameters is not None:
        if 'tolerance' in parameters:
            tol = parameters['tolerance']
        if 'maxiter' in parameters:
            maxiter = parameters['maxiter']
        if 'dogleg' in parameters:
            applyDogleg = parameters['dogleg']
        if 'radius' in parameters:
            radius = parameters['radius']
        if 'initBfgs' in parameters:
            initBfgs = parameters['initBfgs']

    logger.detailed('** Optimization: BFGS with trust region')
    return alg.bfgsTrustRegion(
        fct,
        x0=initBetas,
        initBfgs=initBfgs,
        delta0=radius,
        eps=tol,
        dl=applyDogleg,
        maxiter=maxiter,
    )


def simpleBoundsNewtonAlgorithmForBiogeme(
    fct, initBetas, bounds, parameters=None
):
    """Optimization interface for Biogeme, based on variants of Newton
    method with simple bounds.

    :param fct: object to calculate the objective function and its derivatives.
    :type fct: algorithms.functionToMinimize

    :param initBetas: initial value of the parameters.
    :type initBetas: numpy.array

    :param bounds: list of tuples (ell,u) containing the lower and upper
                   bounds for each free
                   parameter. Note that this algorithm does not support bound
                   constraints.
                   Therefore, all the bounds must be None.
    :type bounds: list(tuples)

    :param parameters: dict of parameters to be transmitted to the
        optimization routine:

        - tolerance: when the relative gradient is below that threshold,
          the algorithm has reached convergence
          (default:  :math:`\\varepsilon^{\\frac{1}{3}}`);
        - steptol: the algorithm stops when the relative change in x
          is below this threshold. Basically, if p significant digits
          of x are needed, steptol should be set to 1.0e-p. Default:
          :math:`10^{-5}`
        - cgtolerance: when the norm of the residual is below that
          threshold, the conjugate gradient algorithm has reached
          convergence (default:  :math:`\\varepsilon^{\\frac{1}{3}}`);
        - proportionAnalyticalHessian: proportion (between 0 and 1) of
          iterations when the analytical Hessian is calculated (default: 1).
        - infeasibleConjugateGradient: if True, the conjugate
          gradient algorithm may generate until termination.  The
          result will then be projected on the feasible domain.  If
          False, the algorithm stops as soon as an infeasible iterate
          is generated (default: False).
        - maxiter: the maximum number of iterations (default: 1000).
        - radius: the initial radius of the trust region (default: 1.0).
        - eta1: threshold for failed iterations (default: 0.01).
        - eta2: threshold for very successful iteration (default 0.9).
        - enlargingFactor: factor used to enlarge the trust region
          during very successful iterations (default 10).

    :type parameters: dict(string:float or int)

    :return: x, messages

        - x is the solution generated by the algorithm,
        - messages is a dictionary describing information about the lagorithm

    :rtype: numpay.array, dict(str:object)

    """

    tol = np.finfo(np.float64).eps ** 0.3333
    steptol = 1.0e-5
    cgtol = np.finfo(np.float64).eps ** 0.3333
    maxiter = 1000
    radius = 1.0
    eta1 = 0.1
    eta2 = 0.9
    proportionTrueHessian = 1.0
    enlargingFactor = 2
    infeasibleConjugateGradient = False

    # We replace the default value by user defined value, if any.
    if parameters is not None:
        if 'tolerance' in parameters:
            tol = parameters['tolerance']
        if 'steptol' in parameters:
            steptol = parameters['steptol']
        if 'cgtolerance' in parameters:
            cgtol = parameters['cgtolerance']
        if 'maxiter' in parameters:
            maxiter = parameters['maxiter']
        if 'radius' in parameters:
            radius = parameters['radius']
        if 'eta1' in parameters:
            eta1 = parameters['eta1']
        if 'eta2' in parameters:
            eta2 = parameters['eta2']
        if 'enlargingFactor' in parameters:
            enlargingFactor = parameters['enlargingFactor']
        if 'proportionAnalyticalHessian' in parameters:
            proportionTrueHessian = parameters['proportionAnalyticalHessian']
        if 'infeasibleConjugateGradient' in parameters:
            infeasibleConjugateGradient = parameters[
                'infeasibleConjugateGradient'
            ]

    if proportionTrueHessian == 1.0:
        logger.detailed(
            '** Optimization: Newton with trust region for simple ' 'bounds'
        )
    elif proportionTrueHessian == 0.0:
        logger.detailed(
            '** Optimization: BFGS with trust region for simple ' 'bounds'
        )
    else:
        logger.detailed(
            f'** Optimization: Hybrid Newton '
            f'{100*proportionTrueHessian}%/BFGS '
            f'with trust region for simple bounds'
        )
    return alg.simpleBoundsNewtonAlgorithm(
        fct,
        bounds=alg.bioBounds(bounds),
        x0=initBetas,
        proportionTrueHessian=proportionTrueHessian,
        infeasibleConjugateGradient=infeasibleConjugateGradient,
        delta0=radius,
        tol=tol,
        steptol=steptol,
        cgtol=cgtol,
        maxiter=maxiter,
        eta1=eta1,
        eta2=eta2,
        enlargingFactor=enlargingFactor,
    )


def bioNewton(fct, initBetas, bounds, parameters=None):
    """Optimization interface for Biogeme, based on Newton's method with simple
    bounds.

    :param fct: object to calculate the objective function and its derivatives.
    :type fct: algorithms.functionToMinimize

    :param initBetas: initial value of the parameters.
    :type initBetas: numpy.array

    :param bounds: list of tuples (ell,u) containing the lower and upper
                   bounds for each free
                   parameter. Note that this algorithm does not support bound
                   constraints.
                   Therefore, all the bounds must be None.
    :type bounds: list(tuples)

    :param parameters: dict of parameters to be transmitted to the
        optimization routine:

        - tolerance: when the relative gradient is below that threshold,
          the algorithm has reached convergence
          (default:  :math:`\\varepsilon^{\\frac{1}{3}}`);
        - steptol: the algorithm stops when the relative change in x
          is below this threshold. Basically, if p significant digits
          of x are needed, steptol should be set to 1.0e-p. Default:
          :math:`10^{-5}`
        - cgtolerance: when the norm of the residual is below that
          threshold, the conjugate gradient algorithm has reached
          convergence (default:  :math:`\\varepsilon^{\\frac{1}{3}}`);
        - infeasibleConjugateGradient: if True, the conjugate
          gradient algorithm may generate until termination.  The
          result will then be projected on the feasible domain.  If
          False, the algorithm stops as soon as an infeasible iterate
          is generated (default: False).
        - maxiter: the maximum number of iterations (default: 1000).
        - radius: the initial radius of the truat region (default: 1.0).
        - eta1: threshold for failed iterations (default: 0.01).
        - eta2: threshold for very successful iteration (default 0.9).
        - enlargingFactor: factor used to enlarge the trust region
          during very successful iterations (default 10).

    :type parameters: dict(string:float or int)

    :return: x, messages

        - x is the solution generated by the algorithm,
        - messages is a dictionary describing information about the lagorithm

    :rtype: numpay.array, dict(str:object)

    """
    if parameters is None:
        parameters = {'proportionAnalyticalHessian': 1}
    else:
        parameters['proportionAnalyticalHessian'] = 1
    return simpleBoundsNewtonAlgorithmForBiogeme(
        fct, initBetas, bounds, parameters
    )


def bioBfgs(fct, initBetas, bounds, parameters=None):
    """Optimization interface for Biogeme, based on BFGS quasi-Newton
    method with simple bounds.

    :param fct: object to calculate the objective function and its derivatives.
    :type fct: algorithms.functionToMinimize

    :param initBetas: initial value of the parameters.
    :type initBetas: numpy.array

    :param bounds: list of tuples (ell,u) containing the lower and upper
                   bounds for each free
                   parameter. Note that this algorithm does not support bound
                   constraints.
                   Therefore, all the bounds must be None.
    :type bounds: list(tuples)

    :param parameters: dict of parameters to be transmitted to the
        optimization routine:

        - tolerance: when the relative gradient is below that threshold,
          the algorithm has reached convergence
          (default:  :math:`\\varepsilon^{\\frac{1}{3}}`);
        - steptol: the algorithm stops when the relative change in x
          is below this threshold. Basically, if p significant digits
          of x are needed, steptol should be set to 1.0e-p. Default:
          :math:`10^{-5}`
        - cgtolerance: when the norm of the residual is below that
          threshold, the conjugate gradient algorithm has reached
          convergence (default:  :math:`\\varepsilon^{\\frac{1}{3}}`);
        - infeasibleConjugateGradient: if True, the conjugate
          gradient algorithm may generate until termination.  The
          result will then be projected on the feasible domain.  If
          False, the algorithm stops as soon as an infeasible iterate
          is generated (default: False).
        - maxiter: the maximum number of iterations (default: 1000).
        - radius: the initial radius of the truat region (default: 1.0).
        - eta1: threshold for failed iterations (default: 0.01).
        - eta2: threshold for very successful iteration (default 0.9).
        - enlargingFactor: factor used to enlarge the trust region
          during very successful iterations (default 10).

    :type parameters: dict(string:float or int)

    :return: x, messages

        - x is the solution generated by the algorithm,
        - messages is a dictionary describing information about the lagorithm

    :rtype: numpay.array, dict(str:object)

    """
    if parameters is None:
        parameters = {'proportionAnalyticalHessian': 0}
    else:
        parameters['proportionAnalyticalHessian'] = 0
    return simpleBoundsNewtonAlgorithmForBiogeme(
        fct, initBetas, bounds, parameters
    )
