# Source code for biogeme.optimization

"""
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 logging
import numpy as np
import scipy.optimize as sc
import biogeme.algorithms as alg
import biogeme.exceptions as excep

logger = logging.getLogger(__name__)

[docs]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

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

"""

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

logger.info('Optimization algorithm: scipy')
# 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.info(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

[docs]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.

"""
logger.info('Optimization algorithm: Newton with line search [LS-newton]')

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.info('** Optimization: Newton with linesearch')
return alg.newtonLineSearch(fct, initBetas, eps=tol, maxiter=maxiter)

[docs]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).

: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.

"""
logger.info('Optimization algorithm: Newton with trust region [TR-newton]')

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
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']

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

[docs]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.

"""
logger.info('Optimization algorithm: BFGS with line search [LS-BFGS]')

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.info('** Optimization: BFGS with line search')
return alg.bfgsLineSearch(
fct, x0=initBetas, initBfgs=initBfgs, eps=tol, maxiter=maxiter
)

[docs]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).

- 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.

"""
logger.info('Optimization algorithm: BFGS with trust region [TR-BFGS]')
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
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 'initBfgs' in parameters:
initBfgs = parameters['initBfgs']

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

[docs]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).
algorithm may generate infeasible solutiona 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).
- 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)

"""
logger.info(
'Optimization algorithm: hybrid Newton/BFGS with simple bounds [simple_bounds]'
)

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

# 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 '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 proportionTrueHessian == 1.0:
logger.info('** Optimization: Newton with trust region for simple bounds')
elif proportionTrueHessian == 0.0:
logger.info('** Optimization: BFGS with trust region for simple bounds')
else:
logger.info(
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,
tol=tol,
steptol=steptol,
cgtol=cgtol,
maxiter=maxiter,
eta1=eta1,
eta2=eta2,
enlargingFactor=enlargingFactor,
)

[docs]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).
- 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)

"""
logger.info(
'Optimization algorithm: Newton with simple bounds [simple_bounds_newton].'
)

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

[docs]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).
- 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 algorithm

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

"""
logger.info('Optimization algorithm: BFGS with simple bounds [simple_bounds_BFGS].')

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

algorithms = {
'scipy': scipy,
'LS-newton': newtonLineSearchForBiogeme,
'TR-newton': newtonTrustRegionForBiogeme,
'LS-BFGS': bfgsLineSearchForBiogeme,
'TR-BFGS': bfgsTrustRegionForBiogeme,
'simple_bounds': simpleBoundsNewtonAlgorithmForBiogeme,
'simple_bounds_newton': bioNewton,
'simple_bounds_BFGS': bioBfgs,
}