line_search.py 2.3 KB
Newer Older
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
import abc

from keepers import Loggable


class LineSearch(object, Loggable):
    """
    Class for finding a step size.◙
    """
    __metaclass__ = abc.ABCMeta

    def __init__(self):

        """
        Parameters
        ----------

        f : callable f(x, *args)
            Objective function.

        fprime : callable f'(x, *args)
            Objective functions gradient.

        f_args : tuple (optional)
            Additional arguments passed to objective function and its
            derivation.
        """

        self.xk = None
        self.pk = None

        self.f_k = None
theos's avatar
theos committed
33
        self.f_k_minus_1 = None
34
35
36
37
38
39
40
41
42
43
        self.fprime_k = None

    def set_functions(self, f, fprime, f_args=()):
        assert(callable(f))
        assert(callable(fprime))

        self.f = f
        self.fprime = fprime
        self.f_args = f_args

theos's avatar
theos committed
44
45
    def _set_coordinates(self, xk, pk, f_k=None, fprime_k=None,
                         f_k_minus_1=None):
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
        """
        Set the coordinates for a new line search.

        Parameters
        ----------
        xk : ndarray, d2o, field
            Starting point.

        pk : ndarray, d2o, field
            Unit vector in search direction.

        f_k : float (optional)
            Function value f(x_k).

        fprime_k : ndarray, d2o, field (optional)
            Function value fprime(xk).

        """

65
66
        self.xk = xk.copy()
        self.pk = pk.copy()
67
68
69
70
71
72
73
74
75
76
77

        if f_k is None:
            self.f_k = self.f(xk)
        else:
            self.f_k = f_k

        if fprime_k is None:
            self.fprime_k = self.fprime(xk)
        else:
            self.fprime_k = fprime_k

78
79
        if f_k_minus_1 is not None:
            f_k_minus_1 = f_k_minus_1.copy()
theos's avatar
theos committed
80
81
        self.f_k_minus_1 = f_k_minus_1

82
83
84
85
86
87
88
89
90
91
92
93
94
    def _phi(self, alpha):
        if alpha == 0:
            value = self.f_k
        else:
            value = self.f(self.xk + self.pk*alpha, *self.f_args)
        return value

    def _phiprime(self, alpha):
        if alpha == 0:
            gradient = self.fprime_k
        else:
            gradient = self.fprime(self.xk + self.pk*alpha, *self.f_args)

95
        return gradient.dot(self.pk)
96
97

    @abc.abstractmethod
theos's avatar
theos committed
98
99
    def perform_line_search(self, xk, pk, f_k=None, fprime_k=None,
                            f_k_minus_1=None):
100
        raise NotImplementedError