-
Notifications
You must be signed in to change notification settings - Fork 50
/
optimization.py
685 lines (538 loc) · 24.2 KB
/
optimization.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
"""
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
from typing import Any
import numpy as np
import scipy.optimize as sc
from biogeme_optimization.bounds import Bounds
from biogeme_optimization.diagnostics import OptimizationResults
from biogeme_optimization.function import FunctionToMinimize
from biogeme_optimization.linesearch import newton_line_search, bfgs_line_search
from biogeme_optimization.simple_bounds import simple_bounds_newton_algorithm
from biogeme_optimization.trust_region import newton_trust_region, bfgs_trust_region
logger = logging.getLogger(__name__)
def scipy(
fct: FunctionToMinimize,
init_betas: np.ndarray,
bounds: list[tuple[float, float]],
variable_names: list[str],
parameters: Any | None = None,
) -> OptimizationResults:
"""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 init_betas: initial value of the Beta parameters
:type init_betas: numpy.array
:param bounds: list of tuples (ell,u) containing the lower and upper bounds
for each free parameter
:type bounds: list(tuple)
:param variable_names: names of the variables. Ignored
here. Included to comply with the syntax.
:type variable_names: list(str)
: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: named tuple:
- betas is the solution found,
- message is a dictionary reporting various aspects
related to the run of the algorithm.
- convergence is a bool which is True if the algorithm has converged
:rtype: OptimizationResult
"""
def f_and_grad(x: np.ndarray) -> tuple[float, np.ndarray]:
fct.set_variables(x)
function_data = fct.f_g()
return function_data.function, function_data.gradient
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, init_betas, 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 OptimizationResults(
solution=results.x, messages=messages, convergence=results.success
)
def newton_linesearch_for_biogeme(
fct: FunctionToMinimize,
init_betas: np.ndarray,
bounds: list[tuple[float, float]],
variable_names: list[str],
parameters: dict[str, Any] | None = None,
) -> OptimizationResults:
"""Optimization interface for Biogeme, based on Newton method.
:param fct: object to calculate the objective function and its derivatives.
:type fct: algorithms.functionToMinimize
:param init_betas: initial value of the parameters.
:type init_betas: 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 will be ignored.
:type bounds: list(tuples)
:param variable_names: names of the variables.
:type variable_names: list(str)
: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: named tuple:
- betas is the solution found,
- message is a dictionary reporting various aspects
related to the run of the algorithm.
- convergence is a bool which is True if the algorithm has converged
:rtype: OptimizationResults
"""
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:
warning_msg = (
'This algorithm does not handle bound constraints. '
'The bounds will be ignored.'
)
logger.warning(warning_msg)
maxiter = 100
if parameters is not None:
if 'maxiter' in parameters:
maxiter = parameters['maxiter']
logger.info('** Optimization: Newton with linesearch')
return newton_line_search(
the_function=fct, starting_point=init_betas, maxiter=maxiter
)
def newton_trust_region_for_biogeme(
fct: FunctionToMinimize,
init_betas: np.ndarray,
bounds: list[tuple[float, float]],
variable_names: list[str],
parameters: dict[str, Any] | None = None,
) -> OptimizationResults:
"""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 init_betas: initial value of the parameters.
: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 will be ignored.
:type bounds: list(tuples)
:param variable_names: names of the variables.
:type variable_names: list(str)
: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: named tuple:
- betas is the solution found,
- message is a dictionary reporting various aspects
related to the run of the algorithm.
- convergence is a bool which is True if the algorithm has converged
:rtype: OptimizationResults
"""
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:
warning_msg = (
'This algorithm does not handle bound constraints. '
'The bounds will be ignored.'
)
logger.warning(warning_msg)
maxiter = 100
apply_dogleg = False
radius = 1.0
if parameters is not None:
if 'maxiter' in parameters:
maxiter = parameters['maxiter']
if 'dogleg' in parameters:
apply_dogleg = parameters['dogleg']
if 'radius' in parameters:
radius = parameters['radius']
logger.info('** Optimization: Newton with trust region')
return newton_trust_region(
the_function=fct,
starting_point=init_betas,
use_dogleg=apply_dogleg,
maxiter=maxiter,
initial_radius=radius,
)
def bfgs_linesearch_for_biogeme(
fct: FunctionToMinimize,
init_betas: np.ndarray,
bounds: list[tuple[float, float]],
variable_names: list[str],
parameters: dict[str, Any] | None = None,
) -> OptimizationResults:
"""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 init_betas: initial value of the parameters.
: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 will be ignored.
:type bounds: list(tuples)
:param variable_names: names of the variables.
:type variable_names: list(str)
: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)
"""
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:
warning_msg = (
'This algorithm does not handle bound constraints. '
'The bounds will be ignored.'
)
logger.warning(warning_msg)
maxiter = 100
init_bfgs = None
if parameters is not None:
if 'maxiter' in parameters:
maxiter = parameters['maxiter']
if 'initBfgs' in parameters:
init_bfgs = parameters['initBfgs']
logger.info('** Optimization: BFGS with line search')
return bfgs_line_search(
the_function=fct,
starting_point=init_betas,
init_bfgs=init_bfgs,
maxiter=maxiter,
)
def bfgs_trust_region_for_biogeme(
fct: FunctionToMinimize,
init_betas: np.ndarray,
bounds: list[tuple[float, float]],
variable_names: list[str],
parameters: dict[str, Any] | None = None,
) -> OptimizationResults:
"""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 init_betas: initial value of the parameters.
: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 will be ignored.
:type bounds: list(tuples)
:param variable_names: names of the variables.
:type variable_names: list(str)
: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)
"""
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:
warning_msg = (
'This algorithm does not handle bound constraints. '
'The bounds will be ignored.'
)
logger.warning(warning_msg)
maxiter = 100
apply_dogleg = False
radius = 1.0
init_bfgs = None
if parameters is not None:
if 'maxiter' in parameters:
maxiter = parameters['maxiter']
if 'dogleg' in parameters:
apply_dogleg = parameters['dogleg']
if 'radius' in parameters:
radius = parameters['radius']
if 'initBfgs' in parameters:
init_bfgs = parameters['initBfgs']
logger.info('** Optimization: BFGS with trust region')
return bfgs_trust_region(
the_function=fct,
starting_point=init_betas,
init_bfgs=init_bfgs,
use_dogleg=apply_dogleg,
maxiter=maxiter,
initial_radius=radius,
)
def simple_bounds_newton_algorithm_for_biogeme(
fct: FunctionToMinimize,
init_betas: np.ndarray,
bounds: list[tuple[float, float]],
variable_names: list[str],
parameters: dict[str, Any] | None = None,
) -> OptimizationResults:
"""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 init_betas: initial value of the parameters.
: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 will be ignored.
:type bounds: list(tuples)
:param variable_names: names of the variables.
:type variable_names: list(str)
: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 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).
- 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)
"""
logger.info(
'Optimization algorithm: hybrid Newton/BFGS with simple bounds [simple_bounds]'
)
cgtol = np.finfo(np.float64).eps ** 0.3333
maxiter = 1000
radius = 1.0
eta1 = 0.1
eta2 = 0.9
proportion_true_hessian = 1.0
enlarging_factor = 2
# We replace the default value by user defined value, if any.
if parameters is not None:
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:
enlarging_factor = parameters['enlargingFactor']
if 'proportionAnalyticalHessian' in parameters:
proportion_true_hessian = parameters['proportionAnalyticalHessian']
if proportion_true_hessian == 1.0:
logger.info('** Optimization: Newton with trust region for simple bounds')
elif proportion_true_hessian == 0.0:
logger.info('** Optimization: BFGS with trust region for simple bounds')
else:
logger.info(
f'** Optimization: Hybrid Newton '
f'{100*proportion_true_hessian}%/BFGS '
f'with trust region for simple bounds'
)
return simple_bounds_newton_algorithm(
the_function=fct,
bounds=Bounds(bounds),
starting_point=init_betas,
variable_names=variable_names,
proportion_analytical_hessian=proportion_true_hessian,
first_radius=radius,
conjugate_gradient_tol=cgtol,
maxiter=maxiter,
eta1=eta1,
eta2=eta2,
enlarging_factor=enlarging_factor,
)
def bio_newton(
fct: FunctionToMinimize,
init_betas: np.ndarray,
bounds: list[tuple[float, float]],
variable_names: list[str],
parameters: dict[str, Any] | None = None,
) -> OptimizationResults:
"""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 init_betas: initial value of the parameters.
: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 variable_names: names of the variables.
:type variable_names: list(str)
: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)
"""
logger.info(
'Optimization algorithm: Newton with simple bounds [simple_bounds_newton].'
)
if parameters is None:
parameters = {'proportionAnalyticalHessian': 1}
else:
parameters['proportionAnalyticalHessian'] = 1
return simple_bounds_newton_algorithm_for_biogeme(
fct, init_betas, bounds, variable_names, parameters
)
def bio_bfgs(
fct: FunctionToMinimize,
init_betas: np.ndarray,
bounds: list[tuple[float, float]],
variable_names: list[str],
parameters: dict[str, Any] | None = None,
) -> OptimizationResults:
"""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 init_betas: initial value of the parameters.
: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 variable_names: names of the variables.
:type variable_names: list(str)
: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 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 simple_bounds_newton_algorithm_for_biogeme(
fct, init_betas, bounds, variable_names, parameters
)
algorithms = {
'scipy': scipy,
'LS-newton': newton_linesearch_for_biogeme,
'TR-newton': newton_trust_region_for_biogeme,
'LS-BFGS': bfgs_linesearch_for_biogeme,
'TR-BFGS': bfgs_trust_region_for_biogeme,
'simple_bounds': simple_bounds_newton_algorithm_for_biogeme,
'simple_bounds_newton': bio_newton,
'simple_bounds_BFGS': bio_bfgs,
}